简体   繁体   English

使用 JavaScript 将 JSON 数组从一种格式转换为另一种格式

[英]Converting JSON array from one format to another using JavaScript

I'm a newbie here and would like some guidance.我是这里的新手,需要一些指导。 How do I convert the JSON array (input) to another JSON array but grouping by id and need just the values of 'id' and 'sid'.如何将 JSON 数组(输入)转换为另一个 JSON 数组但按 id 分组并且只需要“id”和“sid”的值。

I have tried using lodash, array.reduce but couldn't get the expected output.我试过使用 lodash、array.reduce 但无法获得预期的 output。

The actual input will be a large JSON array and any suggestions on how to solve this efficiently will be much appreciated.实际输入将是一个大的 JSON 数组,非常感谢任何有关如何有效解决此问题的建议。

Input:输入:

[
    {
        "id": "11111",
        "sid": "12345"
    },
    {
        "id": "22222",
        "sid": "23456"
    },
    {
        "id": "22222",
        "sid": "34567"
    }
]

Expected Output:预计 Output:

[
    {
        "11111": [
            "12345"
        ]
    },
    {
        "22222": [
            "23456",
            "34567"
        ]
    }
]

lodash: lodash:

_.groupBy(array, x => x.id);

lodash output: lodash output:

{
  '11111': [
    { id: '11111', sid: '12345' }
  ],
  '22222': [
    { id: '22222', sid: '23456' },
    { id: '22222', sid: '34567' } 
  ]
}

array.reduce: array.reduce:

const groupById = (array, key, value) => {
  return array.reduce((result, currentValue) => {
    (result[currentValue[key]] = result[currentValue[key]] || []).push(
      currentValue[value]
    );
    return result;
  }, {});
};

array.reduce output: array.reduce output:

{
    "11111": [
        "12345"
    ],
    "22222": [
        "23456",
        "34567"
    ]
}

You could store the object with wanted key for grouping and take the values later.您可以将 object 与想要的键一起存储以进行分组,并在以后获取值。

 const data = [{ id: "11111", sid: "12345" }, { id: "22222", sid: "23456" }, { id: "22222", sid: "34567" }], result = Object.values(data.reduce((r, { id, sid }) => { r[id]??= { [id]: [] }; r[id][id].push(sid); return r; }, {})); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

You can group the values by id with the function Array.prototype.reduce and then extract the grouped values by using the function Object.values .您可以使用 function Array.prototype.reduceid对值进行分组,然后使用 function Object.values提取分组值。

 const data = [{ id: "11111", sid: "12345" }, { id: "22222", sid: "23456" }, { id: "22222", sid: "34567" }], result = Object.values(data.reduce((a, { id, sid }) => { (a[id] || (a[id] = {[id]: []}))[id].push(sid); return a; }, {})); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM