Reputation: 14434
I basically want to pull out the first object within an array and get it's name. The only challenge here is that I'm trying to destructure this within a parent object:
const exampleObject = {
collection: [{
name: "First Object",
}, {
name: "Second Object",
}],
};
const {
collection: [firstObject: {
name
}]
} = exampleObject;
console.log(firstObject);
Is sort of thing possible?
Upvotes: 1
Views: 2191
Reputation: 37755
You need to switch it to:
{name: firstObject}
| |________ New variable name
|
|_________________ Property name
const exampleObject = {collection: [{name: "First Object",}, {name: "Second Object",}],}
const { collection: [{ name: firstObject }] } = exampleObject
console.log(firstObject)
Upvotes: 6
Reputation: 311
If you need the name of first object you should write
const {
collection: [{ name }]
} = exampleObject;
console.log(name);
Upvotes: 1