简体   繁体   English

对 Object.property.property 的解构赋值

[英]Destructuring assignment to Object.property.property

In the following example, destructuring assignment can be used as const {key1, key2, key3} = obj;在下面的例子中,解构赋值可以用作const {key1, key2, key3} = obj; . .
However, is it possible to directly assign key1 , key2 , key3 (without looping) to their newValue using destructuring assignment?但是,是否可以使用解构赋值直接将key1key2key3 (不循环)分配给它们的newValue

const obj = {
  key1: {oldValue: '1', newValue: '2'},
  key2: {oldValue: '3', newValue: '4'},
  key3: {oldValue: '5', newValue: '6'},
}


const key1 = obj.key1.newValue;
const key2 = obj.key2.newValue;
const key3 = obj.key3.newValue;

It's ugly - but it has to be:p它很丑 - 但它必须是:p

 const obj = { key1: {oldValue: '1', newValue: '2'}, key2: {oldValue: '3', newValue: '4'}, key3: {oldValue: '5', newValue: '6'}, }; const { key1:{newValue:key1} = {}, key2:{newValue:key2} = {}, key3:{newValue:key3} = {}, key4:{newValue:key4} = {} } = obj; console.log(key1, key2, key3, key4);

This is of course not without loops but maybe still a short way of writing it:这当然不是没有循环,但可能仍然是一种简短的编写方式:

 const obj = { key1: {oldValue: '1', newValue: '2'}, key2: {oldValue: '3', newValue: '4'}, key3: {oldValue: '5', newValue: '6'} }; const {key1,key2,key3}=Object.fromEntries(Object.entries(obj).map(([k,v])=>[k,v.newValue])) console.log(key1,key2,key3);

 const obj = { key1: {oldValue: '1', newValue: '2'}, key2: {oldValue: '3', newValue: '4'}, key3: {oldValue: '5', newValue: '6'}, } const {key1: {newValue:key1}, key2: {newValue:key2}, key3: {newValue:key3}} = obj; console.log(key1, key2, key3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM