How to filter an object with its values in ES6

前端 未结 8 1562
日久生厌
日久生厌 2020-12-11 01:53

What is the best way to filter an object this way in ES6?

Starting data:

const acceptedValues = [\"value1\",\"value3\"]
const myObject = {
    prop1:         


        
相关标签:
8条回答
  • 2020-12-11 02:33

    Just to build on top of @Nenad Vracar good answer you could use an object instead of the Array with includes for faster lookup:

    const acceptedValues = ["value1", "value3"];
    const myObject = {
      prop1: "value1",
      prop2: "value2",
      prop3: "value3"
    };
    
    const lookup = acceptedValues.reduce( (memo, prop) => {
      memo[prop] = true;
      return memo;
    });
    
    const filteredObject = Object.keys(myObject).reduce((filtered, key) => {
      if(lookup[myObject[key]]){
        filtered[key] = myObject[key];
      }
      return filtered;
    }, {});
    
    console.log(filteredObject);

    Nor that the includes doesn't do the job, but I thought to provide an alternative view.

    0 讨论(0)
  • 2020-12-11 02:33

    Using a simple for loop and get object by key.

    const acceptedValues = ["value1","value3"]
    const myObject = {
        prop1:"value1",
        prop2:"value2",
        prop3:"value3"
    }
    
    Object.prototype.getKeyByValue = function( value ) {
        for( var prop in this ) {
            if( this.hasOwnProperty( prop ) ) {
                 if( this[ prop ] === value )
                     return prop;
            }
        }
    }
    
    for (var i in acceptedValues) {
      if (myObject.getKeyByValue(acceptedValues[i])){
        console.log(acceptedValues[i]);
      }
    }

    0 讨论(0)
提交回复
热议问题