0
votes

I need the value of keys in object arrA to be copied from arrB based on key name. Here are my two objects:

let arrA = {
    'aaa':'',
    'bbb':'',
    'ccc':''
}
let arrb = {
    'aaa':'111',
    'bbb':'222',
    'ccc':'333',
    'ddd':'444',
    'eee':'555',
    ...
}

How do I do this with the ES6 deconstructive assignment:

arrA = {
    'aaa':'111',
    'bbb':'222',
    'ccc':'333'
}
3

3 Answers

3
votes

Using destructing assignment, you'd have to explicitly define each property you'd want to copy:

let arra = {
  'aaa': '',
  'bbb': '',
  'ccc': ''
};
let arrb = {
  'aaa': '111',
  'bbb': '222',
  'ccc': '333',
  'ddd': '444',
  'eee': '555',
};

({aaa: arra.aaa, bbb: arra.bbb, ccc: arra.ccc} = arrb);

console.log(arra);

However, this code is very repetitive, and the worst part is that it's explicit with what gets copied.

1
votes

The purpose of destructuring is to pull out variables from the object into your local scope. Learn more about destructuring here. You're probably better off solving this problem with different tools.

Using a combination of different functions, you can do this instead:

let arra = {
    'aaa':'',
    'bbb':'',
    'ccc':''
}
let arrb = {
    'aaa':'111',
    'bbb':'222',
    'ccc':'333',
    'ddd':'444',
    'eee':'555'
}

const result = Object.fromEntries(
  Object.keys(arra)
    .map(key => [key, arrb[key]])
)

console.log(result)

First, I'm grabbing all of the keys from arra with Object.keys(), then I'm creating a list of pairs using the .map() function, and finally I'm turning the pairs into a new object with Object.fromEntries()

0
votes

Lodash's pick() is your friend here (because life is too short to write boring boilerpllate code):

You just npm install lodash and say:

const _ = require('lodash');

_.pick( sourceObjectOrArray, arrayOfDesiredPaths ); 

Like this:

const _      = require('lodash');
const source = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
  e: 5,
  f: 6,
  g: 7,
}
const picked = _.pick( source, ['a','c','e'] );

console.log( JSON.stringify(picked) );

And you'll find picked is what you'd expect:

{
  a: 1,
  c: 3,
  e: 5
}