0

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?

adiga
  • 34,372
  • 9
  • 61
  • 83
Tom Rudge
  • 3,188
  • 8
  • 52
  • 94
  • 1
    Have you tried anything? You might want to take a look at [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/q/2274242/215552) for starters... And [Group array of object nesting some of the keys with specific names](https://stackoverflow.com/q/48425797/215552). – Heretic Monkey Feb 08 '19 at 14:23
  • Yes I have tried a few things. Thanks though for the link, upvote – Tom Rudge Feb 08 '19 at 14:40

2 Answers2

2

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)
adiga
  • 34,372
  • 9
  • 61
  • 83
1

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);
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40