简体   繁体   中英

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'.

I have tried using lodash, array.reduce but couldn't get the expected output.

The actual input will be a large JSON array and any suggestions on how to solve this efficiently will be much appreciated.

Input:

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

Expected 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"
    ]
}

You could store the object with wanted key for grouping and take the values later.

 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 .

 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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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