Boky Boky - 2 months ago 11
React JSX Question

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?

Answer

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