1

I have a scenario, where I receive an obj from a promise, and need to add some keys of this object to another object. For example:

// Received from promise
object_1 = {
    name: 'SH'
};

// Want to add object_1.name to object_2 
object_2 = {
    id: 1234
};

Normally I could do like following, but I want to do it with object destructuring

object_2.name = object_1.name;

to have:

object_2 = {
    id: 1234,
    name: 'SH'
};   
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
shwz
  • 426
  • 1
  • 6
  • 22
  • You might want object spread instead, which requires only one line, unlike destructuring? `const object_2 = { id: 1234, ...object_1 }` – CertainPerformance Jun 02 '18 at 07:25
  • @CertainPerformance this could be a part of the `module.exports` also where the `object_1` is being exported and then imported in another file. – Ankit Agarwal Jun 02 '18 at 07:26
  • 1
    There is really no good reason to use destructuring for assigning a single property. – Bergi Jun 02 '18 at 09:19
  • Whilst @CertainPeformances suggestion in the comment above achieves your desired result given in your question... You need to be mindful that if `object_1` also has an `id` property, lets say with value of `6789` - then your _object_2_ will be `{id: 6789, name: "SH"}`. i.e. The `id` in `object_1` will take precedence over the specified `id: 1234`. – RobC Jun 02 '18 at 12:20

2 Answers2

3

You could use a destructuring assignment to a target object/property with a object property assignment pattern [YDKJS: ES6 & Beyond].

var object_1 = { name: 'SH' },
    object_2 = { id: 1234 };

({ name: object_2.name } = object_1);

console.log(object_2);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can achieve the expected output by using object destructing like this:

// Received from promise
object_1 = {
    name: 'SH'
};

// Want to add object_1.name to object_2 
object_2 = {
    id: 1234
};

object_2 = {
  ...object_2,
  ...object_1
}
Jyoti Arora
  • 131
  • 8