如何将一个对象数组转换为另一个对象数组?

时间:2019-06-12 11:38:03

标签: javascript

我有一个这样的对象数组:

const arr = [
  {
    date: "12-09-2018",
    text: "something",
    type: "free",
    id: "dsadsadada"
  },
  {
    date: "12-09-2018",
    text: "something1",
    type: "premium",
    id: "fdss4a4654"
  }
]

,我想将此数组转换为这个数组:

const arr2 = [
    {
      date: "12-09-2018",
      data: [
        {
          type: "free",
          id: "dsadsadada",
          text: "something"
         },
         {
            type: "premium",
            id: "fdss4a4654",
            text: "something1"
        }
    ]
  }
]

因此,在这种情况下,我每天都会有一组数据。最好的方法是什么?谢谢:)

4 个答案:

答案 0 :(得分:0)

 const tempData = {};
 const arr = [
  {
    date: "12-09-2018",
    text: "something",
    type: "free",
    id: "dsadsadada"
  },
  {
    date: "12-09-2018",
    text: "something1",
    type: "premium",
    id: "fdss4a4654"
  }
]
arr.forEach(d=> {
if(!tempData[d.date]) tempData[d.date] = [];
const _data = {...d};
delete _data.date;
tempData[d.date].push(_data);
})
const arr2 = Object.keys(tempData).map(date=> {
  return {date, data: tempData[date]}
})

答案 1 :(得分:0)

使用reduce

const arr = [
    {
      date: "12-09-2018",
      text: "something",
      type: "free",
      id: "dsadsadada"
    },
    {
      date: "12-09-2018",
      text: "something1",
      type: "premium",
      id: "fdss4a4654"
    }
  ];

  const output = Object.values(arr.reduce((accu, {date, ...rest}) => {
    if(!accu[date]) {
        accu[date] = {date, data: []};
    }
    accu[date].data.push(rest);
    return accu;
  }, {}));

  console.log(output);

答案 2 :(得分:0)

您需要使用reduce类的Array方法,就像在代码段中一样

const arr = [{
    date: "12-09-2018",
    text: "something",
    type: "free",
    id: "dsadsadada"
  },
  {
    date: "12-09-2018",
    text: "something1",
    type: "premium",
    id: "fdss4a4654"
  }
]

const group = arr.reduce((arr, {
  date,
  ...value
}) => {
  let group = arr.find(grp => grp.date === date);
  if (!group) {
    group = {
      date,
      data: []
    }
    arr.push(group)
  }
  group.data.push(value)
  return arr;
}, [])

console.log(group)

答案 3 :(得分:-1)

我会考虑使用地图:

const dates = new Map();

arr.forEach(({ date, text, type, id}) => {

    if (dates.has(date)) {
        dates.set(date, [{ text, type, id}].concat(dates.get(date)))
    }
    else {
        dates.set(date, [{ text, type, id}])
    }
})