Nodejs-在解构时操纵属性
Nodejs- Manipulating properties while destructuring
我正在寻找一种在解构对象时操作数据的巧妙方法。
看看下面的代码:
let employee = {
name: 'John Doe',
birthday: '1980/01/01', // yyyy/MM/dd format
department: 'R&D'
}
const { name, birthday, department } = employee
console.log(`${name} is working under ${department} and their birthday is on ${birthday}.`)
假设我想调整它以显示他们的年龄而不是他们的生日,我有一种方法可以计算他们的年龄,称为 calcAge
。
我希望代码围绕这个(或等效于):
let employee = {
name: 'John Doe',
birthday: '1980/01/01', // yyyy/MM/dd format
department: 'R&D'
}
// Option 1: Current state:
const { name, birthday , department } = employee
const age = calcAge(birthday)
// Option 2: Required state:
// const { name, age: calcAge(birthday), department } = employee
// Note this: ^^^^^^^^^^^^^^^^^^^^^^
console.log(`${name} is working under ${department} and they are ${age} years old.`)
希望这是有道理的,如果您有任何问题,请随时提问。
遗憾的是,在解构对象时无法操作数据。赋值解构的唯一目的是能够赋值而不是操纵它们。
此外,在赋值解构期间操作数据可能会导致混乱和难以阅读。
我正在寻找一种在解构对象时操作数据的巧妙方法。 看看下面的代码:
let employee = {
name: 'John Doe',
birthday: '1980/01/01', // yyyy/MM/dd format
department: 'R&D'
}
const { name, birthday, department } = employee
console.log(`${name} is working under ${department} and their birthday is on ${birthday}.`)
假设我想调整它以显示他们的年龄而不是他们的生日,我有一种方法可以计算他们的年龄,称为 calcAge
。
我希望代码围绕这个(或等效于):
let employee = {
name: 'John Doe',
birthday: '1980/01/01', // yyyy/MM/dd format
department: 'R&D'
}
// Option 1: Current state:
const { name, birthday , department } = employee
const age = calcAge(birthday)
// Option 2: Required state:
// const { name, age: calcAge(birthday), department } = employee
// Note this: ^^^^^^^^^^^^^^^^^^^^^^
console.log(`${name} is working under ${department} and they are ${age} years old.`)
希望这是有道理的,如果您有任何问题,请随时提问。
遗憾的是,在解构对象时无法操作数据。赋值解构的唯一目的是能够赋值而不是操纵它们。
此外,在赋值解构期间操作数据可能会导致混乱和难以阅读。