Destructuring assignment to Object.property.property

Viewed 33

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;
3 Answers

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

Related