javascript - 解构 javascript - 写得更好

标签 javascript

我有这样一个数组,并且相同的 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/

相关文章:

javascript - 单击页面上的电子邮件链接的软件?

javascript - 在 HTML5/js/PHP/CSS 中是否有一种标准的编程方式来创建可重用的对象?

javascript - yyyy-mm-dd 格式的两天之间的差异(以天为单位)?

javascript - Zurb Foundation 6 - 轨道不起作用

javascript - 为什么使用 innerHTML 向 DOM 追加大量元素比 JQuery 的 append() 函数慢?

javascript - 我的碰撞检测出了什么问题?

javascript - 使用 react 更改列表中的事件元素

javascript - 如何从 JQuery Ajax 响应设置 <a> 的内容?

javascript - 如何在标签的 "style"中使用 Javascript 变量?

javascript - 希望切换到 VS 2013/MVC 进行 Web 开发但需要支持 IE8