我无法将嵌套值移动到一个级别。我想将name属性移动到一个级别,如何转换此
[{
date: "1/11",
collections: [{
device: {name: "camera 1"},
count: 10
},{
device: {name: "camera 2"},
count: 20
},{
device: {name: "camera 3"},
count: 30
}]
}]
到此?
[{
date: "1/11",
data: [{
camera: "camera 1",
count: 10
},{
camera: "camera 2",
count: 20
},{
camera: "camera 3",
count: 30
}]
}]
答案 0 :(得分:1)
您需要映射数组,然后映射内部集合数组。
注意:此解决方案使用proposal-object-rest-spread,需要Babel的Object rest spread transform才能正常工作。
const data = [{"date":"1/11","collections":[{"device":{"name":"camera 1"},"count":10},{"device":{"name":"camera 2"},"count":20},{"device":{"name":"camera 3"},"count":30}]}];
const result = data.map(({ collections, ...o }) => ({
...o,
data: collections.map(({ device, ...r }) => ({
...r,
camera: device.name
}))
}));
console.log(result);

答案 1 :(得分:1)
我不确定你的主要对象是数组还是简单对象。我已将您的对象视为数组。我做的是
data
。它的值是一个数组collections
中的对象作为所需结构中的对象填充数据数组({camera: ..., count:...}
)collections
。 (如果你想保留它,那么删除该行)
const yourData = [{
date: "1/11",
collections: [{
device: {
name: "camera 1"
},
count: 10
}, {
device: {
name: "camera 2"
},
count: 20
}, {
device: {
name: "camera 3"
},
count: 30
}]
}];
// using ES5+ syntax
// 1. map through your objects
yourData.map(el => {
// 2. set data array
el.data = [];
// 3. populate with required objects in correct structure
el.collections.forEach(o => {
el.data.push({
camera: o.device.name,
count: o.count
});
});
// 4. remove the old data
delete el.collections;
});
console.log(yourData);

[{ date: "1/11", data: [{ camera: "camera 1", count: 10 },{ camera: "camera 2", count: 20 },{ camera: "camera 3", count: 30 }] }]