关于js对象数组的合并问题

怎么样才能把

var dd =[ [
        {
          linenId: '2222',
          attributeSonName: '布料'
        },
        {
          linenId: '11111',
          attributeSonName: '布料'
        },
         {
          linenId: '333',
          attributeSonName: '古田路'
        },
        {
          linenId: 'LINENSON002111',
          attributeSonName: '皮料'
        },
        {
          linenId: 'LINENSON003111',
          attributeSonName: '皮料'
        },
        {
          linenId: '111',
          attributeSonName: '渣渣会'
        },
        {
          linenId: '12222',
          attributeSonName: '222渣渣会'
        }
      ],
      [
       {
          linenId: '2222',
          attributeSonName: '布料'
        },
        {
          linenId: '11111',
          attributeSonName: '布料'
        },
         {
          linenId: '333',
          attributeSonName: '古田路'
        },
        {
          linenId: '12222',
          attributeSonName: '222渣渣会'
        }
      ] ]

如何转化 才能得到下形式 根据attributeSonName相同然后把lineId push到一个数组中

        var cc =[ [
        {
          linenId: [2222,11111],
          attributeSonName: '布料'
        },
         {
          linenId: [333],
          attributeSonName: '古田路'
        },
        {
          linenId: [LINENSON002111,LINENSON003111],
          attributeSonName: '皮料'
        },
      ],
      [
       {
          linenId: [2222,11111],
          attributeSonName: '布料'
        },
        {
          linenId: [12222],
          attributeSonName: '222渣渣会'
        }
      ] ]
阅读 2.2k
3 个回答

参考一下lodash/groupBy实现

不太理解题主为什么要用一个二维数组来表示,实际上题主的问题跟二维数组没有任何关系对么?
想到两个方法:
1.暴力法
遍历数组,数组的每一项都与其他所有项做对比,如果attributeSonName相同,那么压入当前项的数组,然后删掉被压入的项

2.键值对
整体思路:把数组转换成key为attributeSonName,value为linenId的对象
遍历数组,将数组一项一项传入obj中。如果遇到obj[attributeSonName]不为undefined的情况,那么将linenId压入。
当然,因为key值是中文字符,要注意字符编码的问题。

最后,其实想跟题主说,这样组织数据不是一个好的组织方法。数据的组织最好都有一个唯一的不变项,比如ID。

var targetData = [];
dd.forEach(data=>{
    targetData.push(Object.values(data.reduce(function(item, data){
        if(item[data.attributeSonName]){
            item[data.attributeSonName]["linenId"].push(data.linenId);
        }else{
            item[data.attributeSonName] = {
                linenId:[data.linenId],
                attributeSonName: data.attributeSonName
            }
        }
        return item;
    },{})));
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题