I am trying to reshape some data to be used in a table. To do this I am mapping over an array and then looping over an object inside of it to create a new object with the data I want in it. The issue Im having is if the object contains more than one object inside of it I only get a new object for the first item.
I am trying to get a new object for each of the objects held inside changedProperties
Can anyone help? / Explain?
Here is a working example:
const MOCK_DATA = [
{
triggeredByID: "d5ae18b7eb6f",
triggeredByName: "name",
changedProperties: {
LastName: {
__oldValue: "Mallory",
__newValue: "Mallorie",
},
Suffix: {
__oldValue: "DO",
__newvValue: "NP",
},
},
createdAt: "2022-06-01T10:20:21.329337652Z",
},
{
triggeredByID: "d5ae18b7eb6f",
triggeredByName: "John",
changedProperties: {
State: {
__oldValue: ["TX", "AL"],
__newValue: ["TX", "AL", "FL"],
},
City: {
__oldValue: "Austin",
__newValue: "San Antonio",
},
},
createdAt: "2022-06-01T10:20:21.329337652Z",
},
];
const changedProperties = MOCK_DATA.map((item, idx) => {
for (const [key, value] of Object.entries(item.changedProperties)) {
return {
field: key,
old: item.changedProperties[key].__oldValue,
new: item.changedProperties[key].__newValue,
name: item.triggeredByName,
createdAt: item.createdAt,
};
}
});
console.log(changedProperties)
CodePudding user response:
Yes, if you return inside a for-loop, its scoped to the function. Meaning you will return from the entire function on the first iteration of your loop. Try this instead:
const changedProperties = MOCK_DATA.map((item, idx) => {
return Object.entries(item.changedProperties).map(([key, value]) => {
return {
field: key,
old: item.changedProperties[key].__oldValue,
new: item.changedProperties[key].__newValue,
name: item.triggeredByName,
createdAt: item.createdAt,
};
}
});
console.log(changedProperties)