我有一个Array
这样的人
[
{
name: "A",
job: ["1", "2"]
},
{
name: "B",
job: ["2"]
},
{
name: "C",
job: []
}
]
如何使用lodash将其展平为类似的内容。
[
{
name: "A",
job: ["1"]
},
{
name: "A",
job: ["2"]
},
{
name: "B",
job: ["2"]
},
{
name: "C",
job: []
}
]
我想到的唯一解决方案是递归迭代。
谢谢。
答案 0 :(得分:2)
如果您的对象不是多层深的,则无需使用递归。
相反,您可以实现此目的而无需lodash和递归。您可以使用.flatMap
获取每个job
数组,然后使用.map
为该job
数组中的每个项目创建一个单独的对象。
请参见以下示例:
const arr = [{name: "A", job: ["1", "2"]}, {name: "B", job: ["2"]}, {name: "C", job: []}];
const spreadArrObj = arr => {
return arr.flatMap(({name, job}) => {
if(job.length < 2) return {name, job}; // if the object is empty or has one one object then return the object
return job.map(elem => ({ // map each element in the job array to its own object
name,
job: [elem]
}));
});
}
console.log(spreadArrObj(arr));
请参阅浏览器与.flatMap
here的兼容性。
答案 1 :(得分:1)
let arr = [{
name: "A",
job: ["1", "2"]
},
{
name: "B",
job: ["2"]
},
{
name: "C",
job: []
}
];
let newArr = [];
for (i = 0; i < arr.length; i++) {
var job = arr[i].job
if (job.length > 0) {
for (j = 0; j < job.length; j++) {
obj = {};
obj.name = arr[i].name;
obj.job = [job[j]];
newArr.push(obj);
}
} else {
obj = {};
obj.name = arr[i].name;
obj.job = [];
newArr.push(obj);
}
}
console.log(newArr);
答案 2 :(得分:1)
您可以使用数组reduce
并检查job
数组的长度。如果大于1,则迭代作业数组并创建一个新对象,然后将其推入累加器
let data = [{
name: "A",
job: ["1", "2"]
},
{
name: "B",
job: ["2"]
},
{
name: "C",
job: []
}
]
let newData = data.reduce(function(acc, curr) {
if (curr.job.length > 1) {
curr.job.forEach(function(item) {
acc.push({
name: curr.name,
job: [item]
})
})
} else {
acc.push(curr)
}
return acc;
}, []);
console.log(newData)