Reputation: 15
I have such an array and the same id is always repeated in objects:
const array = [
{
id: 1,
name: "test",
},
{
id: 1,
name: "test2",
}
]
and I would like to assign id to the variable, but I would like to do it nicer than:
const { id } = array[0];
how to do it? and is it possible?
Upvotes: 1
Views: 32
Reputation: 1074999
and I would like to assign id to the variable
There are two id
s in that example. Your version is fine, but you can also use array destructuring on top of the object destructuring:
const [{id}] = array; // For the first one
//or
const [, {id}] = array; // For the second one
const array = [
{
id: 1,
name: "test",
},
{
id: 2, // *** Note I changed it
name: "test2",
}
];
{
const [{id}] = array;
console.log("First one:", id);
}
{
const [, {id}] = array;
console.log("Second one:", id);
}
If you want to grab it from an arbitrary index, rather than a bunch of commas (like const [, , , , , {id}] =...
), you can use object destructuring (since arrays are objects):
const {23: {id}} = array; // Same as const {id} = array[23];
const array = Array.from({length: 24}, (_, i) => ({id: i + 1, name: `Test ${i + 1}`}));
const {23: {id}} = array; // Same as const {id} = array[23];
console.log("At index 23:", id);
Upvotes: 3