I'm wondering how to destructure an array of objects. I'm attempting to destructure country
from the partner
array. It is a project requirement that partner
be an array of objects, even though there should only ever be one partner country per obj.
arr = [
{ title: "Title A",
desc: "Desc A",
role: {role_desc: "Role Desc A", role_name: "Role A"},
partner: [{country: "Brazil", region: "SA"}]
},
{ title: "Title B",
desc: "Desc B",
role: {role_desc: "Role Desc B", role_name: "Role B"},
partner: [{country: "US", region: "NA"}]
}
]
I am able to populate a table with data for all fields except partner
.
arr.map(
({ title, desc, role: {role_name}, partner: [{country}] }) =>
({ title, desc, role: {role_name}, partner: [{country}] })
);
I've referred to Destructure object properties inside array for all elements and Destructuring an array of objects with es6, and it looks like it is not possible to do this without transforming the data first.
Any help would be appreciated (and apologies for the dupe).
I was overlooking a very simple answer due to an equally simple error:
arr.map(
({ title, desc, role: {role_name}, partner}) =>
({ title, desc, role: {role_name}, partner: (partner[0] && partner[0].country) || 'Undefined' })
);
Every item in the array did not necessarily have a "country" property. For certain items, partner
is just an empty array. The above fixed the issue.
I agree that it doesn't make sense to make partner
an array if it will only ever contain one object. Client requirements, however.