使用现有数据格式化新阵列-问题

时间:2018-10-12 14:04:41

标签: javascript arrays

我正在尝试从具有的数据对象中创建一个新数组,如下所示:

const data= {
  periods: [{
    month: 'January',
    types: [
      {
        name: 'sick leave',
        difference: '14',
        revisioned: '7000',
        paid: '5000',
      },
      {
        name: 'holiday',
        difference: '12',
        revisioned: '4000',
        paid: '6000',
      },
    ],
    received: '3000',
    taken: '2000',
    result: '0',
  },
  {
    month: 'February',
    types: [
      {
        name: 'sick leave',
        difference: '5',
        revisioned: '100',
        paid: '200',
      },
      {
        name: 'holiday',
        difference: '4',
        revisioned: '300',
        paid: '232',
      },
    ],
    received: '-2000',
    taken: '2000',
    result: '0',
  }],
};

我想做的是,获取该对象并获取属性typesreceivedtakenresult,并从每个属性值创建一个数组,该数组将是新数组中对象的属性。新数组的最终结果将如下所示:

[
  {
    name: 'sick_leave_difference',
    result: ['14', '5'],
  },
  {
    name: 'sick_leave_revisioned',
    result: ['7000', '100'],
  },
  {
    name: 'sick_leave_paid',
    resultat: '[5000, 200]',
  },
  {
    name: 'holiday_difference',
    resultat: ['12', '4'],
  },
  {
    name: 'holiday_revisioned',
    result: ['4000', '300'],
  },
  {
    name: 'holiday_paid',
    result: '[6000, 232]',
  },
  {
    name: 'received',
    resultat: ['3000', '-2000'],
  },
  {
    navn: 'taken',
    result: ['2000', '2000'],
  },
  {
    name: 'result',
    result: ['0', '0'],
  },
];

问题在于属性类型包含一个数组,并且该属性与其他属性不同,因此我不确定如何实现这一点,也不确定是否优雅?

1 个答案:

答案 0 :(得分:1)

使用Array.reduce()提取并展平types数组。减少展平的数组,并使用entries迭代每个对象的Array.forEach()。创建结果对象(如果不存在),然后添加结果。使用Object.values()提取回数组:

const data= {"periods":[{"month":"January","types":[{"name":"sick leave","difference":"14","revisioned":"7000","paid":"5000"},{"name":"holiday","difference":"12","revisioned":"4000","paid":"6000"}],"received":"3000","taken":"2000","result":"0"},{"month":"February","types":[{"name":"sick leave","difference":"5","revisioned":"100","paid":"200"},{"name":"holiday","difference":"4","revisioned":"300","paid":"232"}],"received":"-2000","taken":"2000","result":"0"}]};

const result = Object.values(data.periods
  .reduce((r, { types }) => [...r, ...types], [])
  .reduce((r, { name, ...props }) => {
    Object.entries(props).forEach(([k, v]) => {
      const navn = `${name} ${k}`.replace(' ', '-');
      
      if(!r[navn]) r[navn] = { navn, result: [] };
      
      r[navn].result.push(v);
    });
    
    return r;
  }, {}));

console.log(result);