Boky
Boky

Reputation: 12064

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?

Upvotes: 1

Views: 3680

Answers (2)

Martin Gottweis
Martin Gottweis

Reputation: 2739

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();

Upvotes: 1

Pugazh
Pugazh

Reputation: 9561

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]));
  }
}

Upvotes: 1

Related Questions