js-map结构和数组互相转换

2024-03-04 00:00:00 javascript js

1.map构造转换为数组并合并数据;

// map转数组
const mapData = {
  '2024-03-04': {
    detail: [
      { titId: '1', name: 'aaa', age: 16 },
      { titId: '2', name: 'ccc', age: 17 },
    ]
   },
   '2024-03-05': {
     detail: [
       { titId: '1', name: 'bbb', age: 18 },
       { titId: '2', name: 'ddd', age: 19 },
     ]
   }
 }
 let arrayData = []
 this.dateDetail = [
   { 'titId': '1', 'titName': 'titName1' },
   { 'titId': '2', 'titName': 'titName2' }
 ]
 for( let i in mapData) {
  mapData[i].detail.forEach(item => {
    item.date = i
  })
    arrayData.push(mapData[i])
 }
 console.log(arrayData)
 arrayData.forEach((item, index) => {
   // 数据处理
   item.detail.forEach((item1, index1) => {
     item1[`date`+(index+1)] = item1.date
     item1[`name`+(index+1)] = item1.name
     item1[`age`+(index+1)] = item1.age
     delete item1.date
     delete item1.name
     delete item1.age
     // 合并数据
     this.dateDetail.forEach((item2, index2) => {
       if(item2.titId === item1.titId) {
         let mergedObj = {...item2, ...item1}
         this.dateDetail.splice(index2, 1, mergedObj)
       }
     })
   })
  })
  console.log(this.dateDetail)
  // 打印后果为:
  // [
  //    { titId: '1', 'titName': 'titName1', date1: '2024-03-04', date2: '2024-03-05', name1: 'aaa', name2: 'bbb', age1: 16, age2: 18 },
  //    { titId: '2', 'titName': 'titName2', date1: '2024-03-04', date2: '2024-03-05', name1: 'ccc', name2: 'ddd', age1: 17, age2: 19 },
  // ]

2.a数组转map

const array = [
  { titId: '1', 'titName': 'titName1', date1: '2024-03-04', date2: '2024-03-05', name1: 'aaa', name2: 'bbb', age1: 16, age2: 18 },
  { titId: '2', 'titName': 'titName2', date1: '2024-03-04', date2: '2024-03-05', name1: 'ccc', name2: 'ddd', age1: 17, age2: 19 }
]
const mapData = {}
array.forEach(item => {
  for (let key in item) {
    console.log(item[key], key, key.slice(4))
    if (key.indexOf('date') > -1) {
      const keyNew = item[key];
      const index = key.slice(4)
      if (!mapData[keyNew]) {
        mapData[keyNew] = []
      }
      mapData[keyNew].push({
        titId: item.titId,
        name: item[`name`+index],
        age: item[`age`+index],
      })
    }
  }
})
console.log(mapData)
// 打印后果为:
//{
//'2024-03-04': [
//    { titId: '1', name: 'aaa', age: 16 },
//    { titId: '2', name: 'ccc', age: 17 },
//],
//'2024-03-05': [
//    { titId: '1', name: 'bbb', age: 18 },
//    { titId: '2', name: 'ddd', age: 19 },
//]

相关文章