输入:
{
"8": [{
"a": 1,
"b": 2
}],
"13": [{
"a": 3,
"b": 4
}]
}
输出
[
{
"a": 1,
"b": 2,
"type": 8
},
{
"a": 3,
"b": 4,
"type": 13
}
]
我试图做嵌套地图,但是没有运气。如果有任何直接的方法,请提供帮助。
result = _.map(input, temp => _.map(temp, obj => _.assign(_.pick(obj, ['a', 'b']))));
答案 0 :(得分:2)
这里应该起作用:
const transform = (input) => Object.entries(input)
.map(([key, val]) => val.map(v => ({...v, type: key})))
.flat()
const input = {"13": [{"a": 3, "b": 4}], "8": [{"a": 1, "b": 2}]}
console.log(transform(input))
与pointed out in another answer一样,如果目标环境为don't support flat
,则可以替换为:
.flat()
与此:
.reduce((a, b) => a.concat(b), [])
答案 1 :(得分:1)
您可以使用_.flatMap()
来迭代对象并展平结果。在flatMap内部,使用_.map()
迭代值,然后使用_.assign()
合并原始对象和类型:
const input = {
"8": [{
"a": 1,
"b": 2
}],
"13": [{
"a": 3,
"b": 4
}]
}
const result = _.flatMap(input, // iterate the object and flatten the results
(values, type) => _.map( // iterate the arrays
values, v => _.assign({ type }, v) // combine the type with the object
)
)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>