Flatten an array inside an array of objects using lodash

问题: 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)

  • 发表于 2019-03-13 11:56
  • 阅读 ( 190 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除