【问题标题】:transform an array of objects into an array containing arrays of objects将对象数组转换为包含对象数组的数组
【发布时间】:2020-03-16 14:39:42
【问题描述】:

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

[{...}, {...}, {...}, {...}, {...}]

一个对象看起来像这样:

{ 
  id: ...
  name: ...
  association: {
    id: ...
  }
}

我想收集具有相同关联 id 的对象并得到一个这样的数组:

[ [ { ... association { id: 1} }, { ... association { id: 1} } ], [ { ... association { id: 2 } } ] ]

我该怎么做?

【问题讨论】:

  • 听起来您正在寻找一个函数,该函数将返回包含提供的关联 ID 的对象数组?
  • 我只想收集关联id属性中包含相同值的不同对象

标签: javascript arrays reactjs


【解决方案1】:

听起来您正在寻找一个函数,该函数将返回包含提供的关联 ID 的对象数组

const data = [{...},{...},{...}]
const getByAssociationID = (source, id) => source.filter(obj => obj.association.id === id)
console.log(getByAssociationID(data, id))

【讨论】:

    【解决方案2】:

    这应该按照您的描述对数据进行分组

    function groupByAssociation(data) {
        return data.reduce((list, value) => {
            let added = false;
    
            list.forEach(group => {
                if(group[0].association.id === value.association.id) {
                    group.push(value);
                    added = true;
                }
            });
    
            if(!added) {
                list.push([ value ]);
            }
    
            return list;
        }, []);
    }
    

    【讨论】:

      【解决方案3】:

      使用forEach 构建和对象,键为association.id,并累积值。

      const data = [
        {
          id: 1,
          name: "blah",
          association: {
            id: "a1"
          }
        },
        {
          id: 2,
          name: "foo",
          association: {
            id: "a2"
          }
        },
        {
          id: 3,
          name: "test",
          association: {
            id: "a2"
          }
        }
      ];
      
      const process = data => {
        const obj = {};
        data.forEach(item => {
          const aId = item.association.id;
          const newItem = obj[aId] || [];
          newItem.push(item);
          obj[aId] = newItem;
        });
        return Object.values(obj);
      };
      
      console.log(process(data));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-06
        • 1970-01-01
        • 2012-12-01
        • 2015-01-03
        • 2022-06-18
        • 2021-05-03
        相关资源
        最近更新 更多