我有这样一个数组,并且相同的 id 总是在对象中重复:
const array = [
{
id: 1,
name: "test",
},
{
id: 1,
name: "test2",
}
]
我想将 id 分配给变量,但我想做得比以下更好:
const { id } = array[0];
怎么办呢?这可能吗?
最佳答案
and I would like to assign id to the variable
该示例中有两个 id
。您的版本很好,但您也可以在对象解构之上使用数组解构:
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);
}
如果你想从任意索引中获取它,而不是一堆逗号(如 const [, , , , , {id}] =...
),你可以使用 object解构(因为数组是对象):
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);
关于javascript - 解构 javascript - 写得更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59138036/