简体   繁体   English

如何 map 真实值将 object 中的 js/lodash 中的对象分隔到数组中?

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

How to convert this using lodash/vanilla javascript如何使用 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.因此,您要做的是迭代所有 object 条目(键 => 值),并且对于其中的每一个,过滤掉虚假值和 map 那些您想要的格式的条目。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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