Nodejs-在解构时操作属性

问题描述 投票:1回答:1

我正在寻找一种在分解对象时操纵数据的聪明方法。看一下下面的代码:

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.`)

希望这很有道理,如果您有任何疑问,请随时提问。

node.js data-manipulation destructuring
1个回答
0
投票

[不幸的是,在分解对象时无法操作数据。分配销毁的唯一目的是能够分配值而不是对其进行操作。

此外,在作业分解过程中操纵数据也可能导致混乱和难以阅读。

© www.soinside.com 2019 - 2024. All rights reserved.