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?

2

2 Answers 2

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)

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

Comments

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

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.