Home > front end >  Converting JSON array from one format to another using JavaScript
Converting JSON array from one format to another using JavaScript

Time:06-22

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

CodePudding user response:

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

CodePudding user response:

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

  • Related