0

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.