我未能将嵌套值上移至一个级别。我想将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
}]
}]
我被困在http://jsfiddle.net/usjyc83u/
最佳答案
您需要先映射数组,然后再映射内部集合数组。
注意:此解决方案使用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);
关于javascript - 通过将嵌套属性提升到一级来转换javascript对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47450138/