【问题标题】:convert nested array to single object with key values Javascirpt将嵌套数组转换为具有键值Javascript的单个对象
【发布时间】:2020-03-20 01:34:09
【问题描述】:

我有一个包含嵌套数组的数组。

嵌套数组可以包含多个对象。

const axisChoiceLoop = _.map(groupByAxisChoice) 

输出:

[
 0: [ {age: 15, count: 242, role: "JW"}] // length 1
 1: [ {age: 21, count: 995, role: "JW"} , {age: 21, count: 137, role: "SW"} ] // length 2
 2: [ {age: 25, count: 924, role: "JW"},  {age: 25, count: 455, role: "SW"}, {age: 25, count: 32, role: "EW"} ]
]

我希望嵌套数组是单个对象,使用它们的角色作为键,并计为值

预期的输出应该是这样的

[ 
  {age :15, JW: 242}, 
  {age: 21, JW:995, SW: 137},
  {age: 25, JW: 924, SW: 445, EW: 32}
]

编辑:我尝试了以下代码

const result = groupByAxisChoice.reduce(
    (obj, item) => Object.assign(obj, { [item.role]: item.count }),
    {},
  )

哪些输出:{ undefined: undefined }

【问题讨论】:

  • 你自己试过什么代码?
  • @jfriend00 我在尝试解决问题时进行了编辑

标签: javascript oop ecmascript-6 lodash


【解决方案1】:

想通了……

const result = groupByAxisChoice.map(items =>
    items.reduce((obj, item) => Object.assign(obj, { age: item.age, [item.role]: item.count }), {}),
)

【讨论】:

    【解决方案2】:

    这是我最终得到的,我知道它没有优化:

    var arr = [
     [ {age: 15, count: 242, role: "JW"}], // length 1
     [ {age: 21, count: 995, role: "JW"} , {age: 21, count: 137, role: "SW"} ], // length 2
     [ {age: 25, count: 924, role: "JW"},  {age: 25, count: 455, role: "SW"}, {age: 25, count: 32, role: "EW"} ]
    ];
    var newArr = [];
    arr.forEach(function(a) {
        var ob = {age: a[0].age};
        a.forEach(d => ob[d.role] = d.count); 
        newArr.push(ob);
    });
    

    我会努力让它变得更好(我不知道如何使用 underscore.js)...

    【讨论】:

      【解决方案3】:

      其他解决方案

      const b = a.map(item => {
      return item.reduce((arr,curr) => {
          return {
            ...arr,
            ['age']: curr['age'],
            [curr['role']]: curr['count'],
          }
        }, {})
      })
      console.log(b)
      

      【讨论】:

        猜你喜欢
        • 2021-11-15
        • 2017-03-27
        • 1970-01-01
        • 1970-01-01
        • 2020-05-03
        • 1970-01-01
        • 2022-12-18
        • 1970-01-01
        • 2015-05-17
        相关资源
        最近更新 更多