Node.js – 在解构时操作属性

huangapple go评论73阅读模式
英文:

Nodejs- Manipulating properties while destructuring

问题

I can help you translate the code portions. Here's the translated code:

我正在寻找一种智能的方法在解构对象时操作数据
看一下以下的代码

let employee =  {
   name: 'John Doe',
   birthday: '1980/01/01', // yyyy/MM/dd 格式
   department: 'R&D'
}

const { name, birthday, department } = employee

console.log(`${name}${department} 工作,他们的生日是 ${birthday}。`)

假设我想要调整这个代码以显示他们的年龄而不是生日我有一个计算他们年龄的方法叫做 `calcAge`

我希望代码围绕这个或等同于这个进行调整
let employee =  {
   name: 'John Doe',
   birthday: '1980/01/01', // yyyy/MM/dd 格式
   department: 'R&D'
}

// 选项 1:当前状态
const { name, birthday , department } = employee
const age = calcAge(birthday)

// 选项 2:所需状态
// const { name, age: calcAge(birthday), department } = employee
// 注意这个:^^^^^^^^^^^^^^^^^^^^^^^

console.log(`${name}${department} 工作,他们已经 ${age} 岁了。`)

这是翻译好的代码,如果您有任何问题,请随时提问。

英文:

I am looking for a smart way to manipulate data while I'm destructuring an object.
Take a look on the following code:

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

Let's say I want to adjust this to show their age instead of their birthday, I have a method that calculates how old they are, which is called calcAge.

I'm expecting the code to revolve around this (or equivalent to):

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

Hope this makes sense, if you have any questions please feel free to ask.

答案1

得分: 1

很遗憾,在解构对象时无法操作数据。赋值解构的唯一目的是能够赋值,而不是操纵数据。

此外,在赋值解构期间操纵数据可能会导致混淆和阅读困难。

英文:

Unfortunately, it's not possible to manipulate the data while you are destructuring an object. The only purpose of the assignment destructuring is to be able to assign values and not manipulate them.

Also, manipulate data during the assignment destructuring could lead to confusion and hard readability.

huangapple
  • 本文由 发表于 2020年1月6日 23:50:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定