json 在javascript中按ID合并词典列表

envsm3lx  于 2022-11-19  发布在  Java
关注(0)|答案(2)|浏览(121)

我有以下输入

[
        {
            "id": "abc",
            "data1": 3,
            "data2": "test1",
        },
        {
            "id": "abc",
            "data1": 4,
            "data2": "test1",
        },
        {
            "id": "xyz",
            "data1": 2,
            "data2": "test2",
        }
]

我想解析这个列表,将data 1转换为list,并将所有具有类似id的data 1添加到其中,如下所示,以创建新的list。

[

        {
            "id": "abc",
            "data1": [3,4],
            "data2": "test1",
        },
        {
            "id": "abc",
            "data1": [2],
            "data2": "test2",
        }
]

我试过几种方法,比如使用Map/Reduce,但是我的解决方案都不起作用。

zzlelutf

zzlelutf1#

const data = [
  {
    id: 'abc',
    data1: 3,
    data2: 'test1',
  },
  {
    id: 'abc',
    data1: 4,
    data2: 'test1',
  },
  {
    id: 'xyz',
    data1: 2,
    data2: 'test2',
  },
];

/**
 * To merge the array of objects by a key
 *
 * @param {any[]} objectArray The input object array
 * @param {string} mergeBy The key for merging the objects
 * @param {string} property The key to which the values should be aggregated
 * @returns
 */
const groupBy = (objectArray, mergeBy, property) =>
  Object.values(
    objectArray.reduce(
      (
        /** @type {{ [x: string]: {}; }} */ acc,
        /** @type {{ [x: string]: any; }} */ obj
      ) => {
        const key = obj[mergeBy];
        const curGroup = acc[key] ?? {};
        // if the key is already exists in the accumulator object
        if (curGroup?.[property] && obj?.[property]) {
          curGroup[property].push(obj[property]);
          return { ...acc, [key]: { ...curGroup } };
        }
        if (!curGroup?.[property] && obj?.[property]) {
          const data = { ...obj } ;
          data[property] = [];
          data[property].push(obj[property]);
          return { ...acc, [key]: { ...data } };
        }
      },
      {}
    )
  );

groupBy(data, 'id', 'data1');
jbose2ul

jbose2ul2#

谢谢大家的帮助。我已经用下面的逻辑解决了

let helper = {}
let result = labels.reduce(function(r, o) {
  var key = o.id
  var outputpDic = {
    'id': o.id,
    'data1': [o.data1],
    'data2': o.data2,
  }

  if (!helper[key]) {
    helper[key] = Object.assign({}, outputpDic)
    r.push(helper[key])
  } else {
    helper[key].data1.push(o.data1)
  }

  return r
}, [])

相关问题