gpt4 book ai didi

javascript - ES6 中对象的高级解构

转载 作者:行者123 更新时间:2023-11-30 14:41:35 25 4
gpt4 key购买 nike

我有以下对象:

personObj = {
_id : '123',
first_name: 'John',
last_name: 'Doe',
}

我想将其解构为以下变量:

id,  <-- _id
name: {
first, <-- first_name
last <-- last_name
}

(我希望 first_name 和 last_name 驻留在“name”对象中)

我试过以下语法:

const {
id: _id,
name: {
first: first_name,
last: last_name
}
} = personObj

但是这会导致错误。我做错了什么?

最佳答案

更新

章节10. Destructuring书的"Exploring ES 6"提供了许多关于如何使用解构的高级示例,并解释了它在内部是如何工作的。

解构可以将值直接提取到对象的属性中。属性不需要存在,但在解构分配发生时所有目标对象必须已经存在。

有了这些知识,回答问题的代码是:

let personObj = {
_id: '123',
first_name: 'John',
last_name: 'Doe',
}

// Create the objects that receive the values on destructuring
let c = { name: {} }

// Do the magic
({ _id: c.id, first_name: c.name.first, last_name: c.name.last } = personObj)

console.log(c)
// {id: "123", name: {first: "John", last: "Doe"}}

使用解构的赋值表达式周围的括号是必需的,如果没有它们,引擎会在第一个 : 处报告语法错误。

原始答案如下。它没有完全回答这个问题,但我把它留在这里供引用。它展示了如何使用 rest properties (...)在解构表达式中,它被 OP 接受,尽管它是不完整的。


原答案

Destructuring with properties renaming反过来工作:原始名称放在冒号之前,新名称在冒号之后。

let personObj = {
_id: '123',
first_name: 'John',
last_name: 'Doe',
}

// Destructure personObj using different names for the properties
const {
_id: id,
first_name: first,
last_name: last
} = personObj


console.log('id: ' + id);
console.log('first: ' + first);
console.log('last: ' + last);

// Output
// id: 123
// first: John
// last: Doe

然后您可以将片段(idfirstlast)组合成一个新对象:

let c = {
id,
name: {
first,
last
}
}

console.log(c);

// Output
// { id: '123', name: { first: 'John', last: 'Doe' } }

更新

与您在问题中描述的最相似的结果可以通过以下方式实现:

let { _id: id, ...name } = personObj

console.log(id)
console.log(name)
// Output
// 123
// { first_name: 'John', last_name: 'Doe' }

但这样 name 的属性使用它们在 personObj 中的相同名称。更重要的是,如果您在 last_name 之后添加您不想在 name 中复制的 personObj 属性,它将不再起作用。

关于javascript - ES6 中对象的高级解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49572952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com