js将数组对象中某个值相同的对象合并成一个新对象

2021-01-16 01:12

阅读:616

标签:each   items   foreach   dex   length   map   find   bsp   i++   

原数组:

var beforeData= [
    { name: "tony", id: "1", age: "20" },
    { name: "jack", id: "2", age: "21" },
    { name: "tony", id: "3", age: "50" },
    { name: "jack", id: "4", age: "10" },
    { name: "mark", id: "5", age: "22" },
    { name: "mark", id: "6", age: "40" }
];

最终数组:

 afterData= [
    {name: "tony",origin: [{ name: "tony", id: "1", age: "20" },{ name: "tony", id: "3", age: "50" }]},
    {name: "jack",origin: [{ name: "jack", id: "2", age: "21" },{ name: "jack", id: "4", age: "10" }]},
    {name: "mark",origin: [{ name: "mark", id: "5", age: "22" },{ name: "mark", id: "6", age: "40" }]}
]

实现方法:

第一种方法:

  var afterData = []
  let tempArr = []
  for (let i = 0; i ) {
    if (tempArr.indexOf(beforeData[i].name) === -1) {
      this.afterData.push({
        name: beforeData[i].name,
        origin: [beforeData[i]]
      })
      tempArr.push(beforeData[i].name)
    } else {
      for (let j = 0; j this.afterData.length; j++) {
        if (this.afterData[j].name == beforeData[i].name) {
          this.afterData[j].origin.push(beforeData[i])
          break
        }
      }
    }
  }
  console.log(this.afterData);

 

第二种方法:

  let afterData = []
  let tempArr = []
  beforeData.map(item => {
    if (tempArr.indexOf(item.name) === -1) {
      afterData.push({
        name: item.name,
        origin: []
      });
      tempArr.push(item.name)
    }
  });
  afterData.map(item => {
    beforeData.map(items => {
      if (item.name == items.name) {
        item.origin.push(items)
      }
    })
  })
  console.log(afterData)

第三种方法:

  var afterData = []
  beforeData.forEach(item => {
    let flag = afterData.find(item1 => item1.name === item.name)
    if (!flag) {
      afterData.push({
        name: item.name,
        origin: [item]
      })
    } else {
      flag.origin.push(item)
    }
  })
  console.log(afterData)

 

 

 

js将数组对象中某个值相同的对象合并成一个新对象

标签:each   items   foreach   dex   length   map   find   bsp   i++   

原文地址:https://www.cnblogs.com/yihengbaobei/p/12933512.html


评论


亲,登录后才可以留言!