I need to change the keys of my object. I could use the map function to change the keys of my outer object. Question is, how can I access the inner object which is in an array as well. In the code below, I need to change the team key to teamName. My structure has to be in the same order.
let myArray = [
{
id: 1,
name: "foo",
Organization: [{ team: "value1" }, { location: "value2" }],
},
{
id: 2,
name: "foo",
Organization: [{ team: "value1" }, { location: "value2" }],
},
];
I can change the keys of the outer array like this if I want to change id to userId.
const newArray = myArray.map((item) => {
return {
userId: item.id,
};
});
But trying to change the keys in the inner list of objects for Organization becomes a problem. What is the best way to modify the inner keys?
import { mapKeys } from 'lodash';
const newArray = myArray.map(item => ({
...item,
Organization: item.Organization.map(org =>
mapKeys(org, (_, key) => (key === 'team' ? 'teamName' : key))
),
}));
You can destruct each Organization and reconstruct it with teamName, as long as team exists.
const newArray = myArray.map(item => ({
...item,
Organization: item.Organization.map(({ team, ...rest }) =>
Object.assign(rest, team ? { teamName: team } : {})
),
}));
[
{
id: 1,
name: 'foo',
Organization: [{ teamName: 'value1' }, { location: 'value2' }],
},
{
id: 2,
name: 'foo',
Organization: [{ teamName: 'value1' }, { location: 'value2' }],
},
];
Couldn't make it more simpler.
console.log(
[{
"id": 1,
"name": "foo",
"Organization": [{
"team": "value1"
}, {
"location": "value2"
}]
},
{
"id": 2,
"name": "foo",
"Organization": [{
"team": "value1"
}, {
"location": "value2"
}]
},
].reduce((a, b) => {
b.Organization[0] = {
teamName: b.Organization[0].team
}
a.push(b)
return a
}, [])
)
If Organization is always an array with 2 elements. Where the first element is an object with the property team, and the second element is an object with the property location. Then the following code does job.
let myArray = [{
"id": 1,
"name": "foo",
"Organization": [{"team": "value1"}, {"location": "value2"}]
}, {
"id": 2,
"name": "foo",
"Organization": [{"team": "value1"}, {"location": "value2"}]
}];
const result = myArray.map((item) => {
const [{ team: teamName }, location] = item.Organization;
return { ...item, Organization: [{ teamName }, location] };
});
console.log(result);
This answer makes use of destructuring assignment. If you don't know what this is I would highly suggest checking out the linked documentation.