简体   繁体   中英

Destructuring assignment to Object.property.property

In the following example, destructuring assignment can be used as const {key1, key2, key3} = obj; .
However, is it possible to directly assign key1 , key2 , key3 (without looping) to their newValue using destructuring assignment?

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

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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