【问题标题】:Convert array of objects into subarrays of objects by a selected property (javascript)通过选定的属性将对象数组转换为对象子数组(javascript)
【发布时间】:2022-02-22 02:40:26
【问题描述】:

我正在寻找一个对象数组,并根据所选对象属性将其转换为子数组数组

例如:

[
  {foo: 1, bar: a}, {foo: 2, bar: b}, {foo: 1, bar: c}, {foo: 2, bar: d}
]

使用 foo 属性创建子数组将变为:

[
  [
    {foo: 1, bar: a}, {foo: 1, bar: c}, 
  ],
  [
    {foo: 2, bar: b}, {foo: 2, bar: d}
  ]
]

我想不出一种有效的方法。我一直求助于创建一组我选择的值的所有唯一属性值,然后多次暴力破解它。

const distinctProperties =  [...new Set(originalArray.map(item => item.foo))]

const newArray = distinctProperties.map(item => originalArray.filter(obj => obj.foo === item))

在此先感谢您的建议!

【问题讨论】:

    标签: javascript arrays object data-manipulation


    【解决方案1】:

    可以使用reduce 完成。您可以将其包裹在另一个函数中,以按您想要的键进行分组。

    这里我根据foo的值进行分组,res会是这样的

    {
      1: [{
      bar: "a",
      foo: 1
    }, {
      bar: "c",
      foo: 1
    }],
      2: [{
      bar: "b",
      foo: 2
    }, {
      bar: "d",
      foo: 2
    }]
    }
    

    然后我将使用 Object.values 来获取您想要的数组格式

    let a =[
      {foo: 1, bar: 'a'}, {foo: 2, bar: 'b'}, {foo: 1, bar: 'c'}, {foo: 2, bar: 'd'}
    ]
    
    let res= Object.values(a.reduce((acc,curr)=> {
        if(!acc[curr.foo])acc[curr.foo]=[];
      acc[curr.foo].push(curr)
        return acc;
    },{}))
    
    console.log(res)

    作为以键名作为输入的通用函数

    let a =[
      {foo: 1, bar: 'a'}, {foo: 2, bar: 'b'}, {foo: 1, bar: 'c'}, {foo: 2, bar: 'd'}
    ]
    
    
    let groupByValue = (arr,key) => {
        return Object.values(arr.reduce((acc,curr)=> {
        if(!acc[curr[key]])acc[curr[key]]=[];
      acc[curr[key]].push(curr)
        return acc;
    },{}))
    }
    
    let res1 = groupByValue(a,'foo')
    let res2 = groupByValue(a,'bar')
    console.log(res1)
    console.log(res2)

    【讨论】:

    • 这是完美的。非常感谢!
    猜你喜欢
    • 2019-02-10
    • 2022-12-08
    • 2019-10-22
    • 2020-09-11
    • 2019-05-29
    • 1970-01-01
    • 2023-02-11
    • 2017-01-14
    • 1970-01-01
    相关资源
    最近更新 更多