【问题标题】:Function to proccess array of objects into another structure? [duplicate]将对象数组处理成另一个结构的函数? [复制]
【发布时间】:2021-10-25 03:15:39
【问题描述】:

我得到一个对象数组:

const inputStructure = [
  {
    state: 'LA',
    insurance: 'Test1'
  },
  {
    state: 'LA',
    insurance: 'Test2'
  },
  {
    state: 'TX',
    insurance: 'Test3'
  }
]

如何将具有相同state 属性的对象分组? 我需要创建一个返回以下结果的函数:

const outputStructure = {
  'LA': {
    state: 'LA',
    insurances: ['Test1', 'Test2']
  },
  'TX': {
    state: 'TX',
    insurances: ['Test3']
  }
}

【问题讨论】:

标签: javascript algorithm


【解决方案1】:

你可以使用:

const inputStructure = [
  {
    state: 'LA',
    insurance: 'Test1'
  },
  {
    state: 'LA',
    insurance: 'Test2'
  },
  {
    state: 'TX',
    insurance: 'Test3'
  }
];

const data = {};

for (const item of inputStructure) {
  if (!data[item.state]) {
    data[item.state] = {
      state: item.state,
      insurances: []
    }
  }
  data[item.state].insurances.push(item.insurance);
}

console.log(data);

【讨论】:

    【解决方案2】:

    可以使用reduce数组方法来实现:

    const inputStructure = [{
        state: 'LA',
        insurance: 'Test1'
      },
      {
        state: 'LA',
        insurance: 'Test2'
      },
      {
        state: 'TX',
        insurance: 'Test3'
      }
    ]
    
    const output = inputStructure.reduce((acc, e) => {
      acc[e.state] = ({
        state: e.state,
        insurances: (acc[e.state]?.insurances || []).concat(e.insurance)
      });
      return acc;
    }, {})
    
    console.log(output)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 2017-12-04
      相关资源
      最近更新 更多