当前位置:网站首页>JS merge duplicate data in array object

JS merge duplicate data in array object

2022-04-23 21:24:00 Sister Chunfeng

Array reorganization data
Source data :
 Insert picture description here
Target data :
 Insert picture description here

//  Source data 
var oldData = [
  {
    
    city_id: 1,
    city_name: ' Beijing ',
    city_img: "http://dfknbdjknvkjsfnvlkjdn.png",
    city_country: " China "
  },
  {
    
    city_id: 2,
    city_name: ' Shanghai ',
    city_img: "http://wergerbe.png",
    city_country: " China "
  },
  {
    
    city_id: 3,
    city_name: ' Guangzhou ',
    city_img: "http://hrthhr.png",
    city_country: " China "
  },
  {
    
    city_id: 4,
    city_name: ' Seattle ',
    city_img: "http://frevfd.png",
    city_country: " The United States "
  },
  {
    
    city_id: 5,
    city_name: ' New York ',
    city_img: "http:// Instead .png",
    city_country: " The United States "
  }
]
 
//  The rule of turning source data into target data first 
var oldDataRule = []
oldData.forEach(el => {
    
  var oldObj = {
    
    name: el.city_country,
    citys:[]
  }
  var cityObj = {
    
    city_name: el.city_name,
    city_img: el.city_img,
    city_id: el.city_id
  }
  oldObj.citys.push(cityObj)
  oldDataRule.push(oldObj)
})
 
/** *  Let's go first , After the merger  * 1、 Source data De duplication  * 2、 The de duplicated data is the same as the source data name Data consolidation of citys */
var newData = []
var newObj = {
    }
oldDataRule.forEach((el, i) => {
    
  if (!newObj[el.name]) {
    
    newData.push(el);
    newObj[el.name] = true;
  } else {
    
    newData.forEach(el => {
    
      if (el.name === oldDataRule[i].name) {
    
        el.citys = el.citys.concat(oldDataRule[i].citys);
        // el.citys = [...el.citys, ...oldDataRule[i].citys]; // es6 grammar 
      }
    })
  }
})
console.log(newData); //  Target data 

result :
 Insert picture description here

版权声明
本文为[Sister Chunfeng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/110/202204200620163928.html