簡體   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