Tom Rudge
Tom Rudge

Reputation: 3272

Transform object array with dynamic key to new array

I have an output from my return array like the below:

[{
    SENIORS: "SINGLE_MAN",
    age: "U21",
    fullName: "John Doe",
    personId: "0001337"
}]

And I need to return this into a new format where I would need to add values from the above into new keys, some nested exactly like the below structure.

[
    {
    "personId": "0001337",
    "Groups": [
        {
        "group":"SENIORS",
        "status" :"SINGLE_MAN"
        }
    ]
    }
]

As you can see I have created a new key called Groups, and 2 new keys within this called group and status. Not sure hows best to create the keys and at the same time assign the old values to them. The original key of senior now needs to be a property of group.

I am using lodash if that can be used?

Upvotes: 0

Views: 252

Answers (2)

Terry Lennox
Terry Lennox

Reputation: 30685

You can re-shape the data fairly easily even without lodash. Also assuming we know the group names in advance.

let a = [{
    SENIORS: "SINGLE_MAN",
    age: "U21",
    fullName: "John Doe",
    personId: "0001337"
}];

let groupNames = ["SENIORS"];

console.log("Input: ", a);

let output = a.map(row => {
    let r = { personId: row.personId };
    r.Groups = groupNames
       .filter(value => Object.keys(row).indexOf(value) !== -1)
       .map(group => {return {group: group, status: row[group]}});

    return r;
});

console.log("Output: ", output);

Upvotes: 1

adiga
adiga

Reputation: 35222

If it always has four properties and only one of them is dynamic, you can isolate the dynamic property using spread syntax. And then use Object.entries and map like this:

const input = [{
  SENIORS: "SINGLE_MAN",
  age: "U21",
  fullName: "John Doe",
  personId: "0001337"
},
{
  JUNIORS: "SINGLE_WOMAN",
  age: "U22",
  fullName: "Jane Doe",
  personId: "0001338"
}]

const output = input.map(({ personId, fullName, age, ...rest}) => {
  const [group, status] = Object.entries(rest)[0];
  return { personId, Groups: [{ group, status }] }
})

console.log(output)

Upvotes: 2

Related Questions