繁体   English   中英

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

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

我是这里的新手,需要一些指导。 如何将 JSON 数组(输入)转换为另一个 JSON 数组但按 id 分组并且只需要“id”和“sid”的值。

我试过使用 lodash、array.reduce 但无法获得预期的 output。

实际输入将是一个大的 JSON 数组,非常感谢任何有关如何有效解决此问题的建议。

输入:

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

预计 Output:

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

lodash:

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

lodash output:

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

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:

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

您可以将 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; }

您可以使用 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