问题:
I have an Array like this
[
{
name: "A",
job: ["1", "2"]
},
{
name: "B",
job: ["2"]
},
{
name: "C",
jo...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I have an Array
like this
[
{
name: "A",
job: ["1", "2"]
},
{
name: "B",
job: ["2"]
},
{
name: "C",
job: []
}
]
How do i flatten it into something like this using lodash.
[
{
name: "A",
job: ["1"]
},
{
name: "A",
job: ["2"]
},
{
name: "B",
job: ["2"]
},
{
name: "C",
job: []
}
]
The only solution coming to my mind is to iterate recursively.
Thanks.
回答1:
You don't need to use recursion if your object isn't multiple levels deep.
Instead, you can achieve this without lodash and recursion. You could use .flatMap
to get each job
array, and then create an individual object for each item within that job
array using .map
.
See example below:
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));
See browser compatibility for .flatMap
here.
回答2:
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);
回答3:
You can use array reduce
and check length of job
array. If it is more than 1 then iterate the job array and create a new object and push it to the accumulator
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)