我有下面的对象数组,其中的一个基础对象带有一组值。
我需要删除所有数据的基础对象,并将其作为下面的“预期结果”。
示例数组
[
{
"100": {
"id": "100",
"name": "Test name 1"
},
"101": {
"id": "101",
"name": "Test name 2"
},
"102": {
"id": "102",
"name": "Test name 3"
}
}
]
预期结果
[
{
"id": "100",
"name": "Test name 1"
},
{
"id": "101",
"name": "Test name 2"
},
{
"id": "102",
"name": "Test name 3"
}
]
答案 0 :(得分:2)
您可以使用Array.map()
进行迭代,并使用Object.values()
获取对象的值,然后通过spreading并将结果展平为单个数组,并将其Array.concat()
压缩为_.flatMap()
:
const data = [{"100":{"id":"100","name":"Test name 1"},"101":{"id":"101","name":"Test name 2"},"102":{"id":"102","name":"Test name 3"}}];
const result = [].concat(...
data.map(o => Object.values(o))
);
console.log(result);
通过lodash,您可以将_.values()
与Full log结合使用:
const data = [{"100":{"id":"100","name":"Test name 1"},"101":{"id":"101","name":"Test name 2"},"102":{"id":"102","name":"Test name 3"}}];
const result = _.flatMap(data, _.values);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>