我有这样的对象数组:
var data = [
{
type : "parent",
name : "A"
},
{
type : "child",
name : "1"
},
{
type : "child",
name : "2"
},
{
type : "parent",
name : "B"
},
{
type : "child",
name : "3"
}
]
我想将子对象移动到父对象中,由父对象拆分(没有来自子对象的给定键属于哪个父对象)。所以它只被父对象分开。为简单起见,我想将数组更改为:
[
{
type : "parent",
name : "A",
child: [
{
type : "child",
name : "1"
},
{
type : "child",
name : "2"
}
]
},
{
type : "parent",
name : "B",
child: [
{
type : "child",
name : "3"
}
]
}
]
我已经阅读了关于 chunk 的 lodash但没用。
最佳答案
您可以使用 native Array.prototype.reduce
函数或 lodash 的 reduce
:
var data = [{
type: "parent",
name: "A"
},
{
type: "child",
name: "1"
},
{
type: "child",
name: "2"
},
{
type: "parent",
name: "B"
},
{
type: "child",
name: "3"
}
];
// If using _.reduce then use:
// var newData = _.reduce(data, function(arr, el) {...}, []);
var newData = data.reduce(function(arr, el) {
if (el.type === 'parent') {
// If el is pushed directly it would be a reference
// from the original data object
arr.push({
type: el.type,
name: el.name,
child: []
});
} else {
arr[arr.length - 1].child.push({
type: el.type,
name: el.name
});
}
return arr;
}, []);
console.log(newData);
更新:使用更新的 ES 语言特性的小改动
const data = [{
type: "parent",
name: "A"
},
{
type: "child",
name: "1"
},
{
type: "child",
name: "2"
},
{
type: "parent",
name: "B"
},
{
type: "child",
name: "3"
}
];
const newData = data.reduce((arr, el) => {
if (el.type === 'parent') {
// If el is pushed directly it would be a reference
// from the original data object
arr.push({...el, child: []});
} else {
arr[arr.length - 1].child.push({...el});
}
return arr;
}, []);
console.log(newData);
关于javascript - 如何使用 lodash/underscorejs 拆分具有特定条件的对象的 javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30645214/