简体   繁体   中英

How to map truthy values to separate objects in js/lodash in an object to array?

How to convert this using lodash/vanilla javascript

const obj = {
'red': {'1': true, '2': false, '3':true},
'green': {'1': false, '2': false, '3':true},
'blue': {'1': true, '2': true, '3':true},
}

to this:

const resultArray = 
[
{'red': '1'}, {'red': '3'},
{'green': '3'},
{'blue': '1'}, {'blue': '2'},
]

Here all the keys whose values are truthy are mapped to 'red', 'green' or 'blue' in array.

So what you want to do is iterate all the object entries (keys => values) and for each of those, filter out the falsy values and map those entries your desired format.

You can then flatten the new array to get the final result you want.

 const obj = { 'red': {'1': true, '2': false, '3':true}, 'green': {'1': false, '2': false, '3':true}, 'blue': {'1': true, '2': true, '3':true}, } const resultArray = Object.entries(obj).map(([ key, vals ]) => Object.entries(vals).filter(([ _, flag ]) => flag).map(([ idx ]) => ({ [key]: idx })) ).flat() console.info(resultArray)

 const obj = { 'red': {'1': true, '2': false, '3':true}, 'green': {'1': false, '2': false, '3':true}, 'blue': {'1': true, '2': true, '3':true}, }; const out = Object.keys(obj).flatMap(color => { return Object.entries(obj[color]).filter(([k, v]) => Boolean(v)).map(([k]) => ({[color]: k})); }); console.log(out);

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