Home > Blockchain >  Match and group object properties in javascript
Match and group object properties in javascript

Time:06-26

i had an object like this i tried to group the object based on the last value of the property but couldn't acheive the desired result. I tried by fetching all the properties and match it using the index value using regex but that didn't worked.

{
q_A.1 : "info",
q_B.1 : "info2",
q_C.1 : "info3",
q_D.1 : "info4",
q_A.2 : "information",
q_B.2 : "information2",
q_C.2 : "information3",
q_D.2 : "information4",
}

i need to group the object like this

[{
q_A.1 : "info",
q_B.1 : "info2",
q_C.1 : "info3",
q_D.1 : "info4",
},
{
q_A.2 : "information",
q_B.2 : "information2",
q_C.2 : "information3",
q_D.2 : "information4",
}]

CodePudding user response:

You can use the reduce method to group the objects.

const data = { "q_A.1": "info", "q_B.1": "info2", "q_C.1": "info3", "q_D.1": "info4", "q_A.2": "information", "q_B.2": "information2", "q_C.2": "information3", "q_D.2": "information4" };

const result = Object.values(
  Object.entries(data).reduce(
    (acc, [k, v]) => (Object.assign((acc[k.split(".")[1]] ??= {}), { [k]: v }), acc),
    {}
  )
);

console.log(result);

Relevant Documentations:

  1. Array.prototype.reduce
  2. Object.entries
  3. Object.values
  4. Object.assign
  5. Nullish coalescing operator (??)
  • Related