Reputation: 151
I need to write a function to transform an object like this:
const foodList = {fruit: {apples: true, pears: false, berries: true}, dairy: {milk: true, cheese: false}, vegetables: {}}
console.log(foodList)
into this:
const result = {fruit: ['apples', 'berries'], dairy: ['milk']}
console.log(result)
I'm trying to convert the nested values to an array where the food key equals true.
Upvotes: 1
Views: 76
Reputation: 17190
Another alternative to get the desired output is to use two nested for
loops to traverse the outer and the inner keys while generating the resulting object. This way, you can also avoid to generate a property
on the resulting object
if all the elements inside a category have the false
value.
const foodList = {
fruit: {apples: true, pears: false, berries: true},
dairy: {milk: true, cheese: false},
vegetables: {},
food: {hamburger: false, spaghetti: false}
};
let res = {};
for (const category in foodList)
{
for (const item in foodList[category])
{
if (foodList[category][item])
{
res[category] = res[category] || [];
res[category].push(item);
}
}
}
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Upvotes: 2
Reputation: 26844
You can use Object.entries
to convert the object into an array. Use reduce
to loop and summarize the array. Use Object.keys
and filter
to get the keys with true value.
const foodList = {"fruit":{"apples":true,"pears":false,"berries":true},"dairy":{"milk":true,"cheese":false},"vegetables":{}}
const result = Object.entries(foodList).reduce((c, [k, v]) => {
let t = Object.keys(v);
if (t.length) c[k] = t.filter(o => v[o]);
return c;
}, {});
console.log(result);
Upvotes: 3