简体   繁体   中英

Loop through array of objects and return object keys

My code is as follows :

let filters = [ 
    {name: "MAKE", values: 
    [
      {
        Volkswagen: {active: true, make: "Volkswagen"},
        Skoda: {active: true, make: "Skoda"}
      }
    ]
    }
]

function getFilterValues(){
  return filters.filter(f => {
    if(f.name == "MAKE"){
      return f.values.filter(i => {
        Object.keys(i).map(key => {
          return key;
        });
      });
    }
  });
}

var div = document.getElementById('output');
div.innerHTML = getFilterValues();

I want to loop through filters to get the object keys.

Thus the result that I want is, in this case Volkswagen, Skoda . But my function getFilterValues doesn't return what I want.

Here is jsfiddle .

Any advice?

You can use Object.keys() to get the list of keys.

 var filters = [{ name: "MAKE", values: [{ Volkswagen: { active: true, make: "Volkswagen" }, Skoda: { active: true, make: "Skoda" } }] }]; for (i = 0; i < filters.length; i++) { if (typeof filters[i].values == "object") { console.log(Object.keys(filters[i].values[0])); } } 

The main problem is with the filter function. You want map since with filter you return true/false whether the element should be included in the resulting code. Check out this diff: https://www.diffchecker.com/CX6hOoxo

This works: https://jsfiddle.net/o93Lm0rc/101/

let filters = [ 
    {name: "MAKE", values: 
    [
        {
            Volkswagen: {active: true, make: "Volkswagen"},
            Skoda: {active: true, make: "Skoda"}
        }
    ]
    }
]

function getFilterValues(){
    return filters.map(f => {
        if(f.name == "MAKE"){
            return f.values.map(i => {
                return Object.keys(i).map(key => {
                    return key;
                });
            });
        }
    });
}


var div = document.getElementById('output');

div.innerHTML = getFilterValues();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM