-2

is it possible to add specific key-value pairs from one object to another object WHILE initializing?

const a = {
    android: {
        time: null,
        diff: null
   }
};

const b = {
    out:{
       x: null,
       context:{
           state: null,
           value: null,
           "a.android key-value pairs right here: 
            time: null,
            diff: null"
       }
    }
 };
Jan
  • 57
  • 1
  • 4
  • 3
    @Adelin That should be the best answer. **Jan**, clarify exactly what you want instead of asking if it's possible. :) – Alex Jul 06 '18 at 13:05
  • 1
    Yes, of course https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically – Abhishek Kumar Jul 06 '18 at 13:08

1 Answers1

7

You may merge two objects like:

Object.assign(b.out.context, a.android)

const a = {
    android: {
        time: null,
        diff: null
   }
};

let b = {
    out:{
       x: null,
       context:{
           state: null,
           value: null,
            time: 1,
            diff: null
       }
    }
 };
 
Object.assign(b.out.context, a.android);
console.log(b);

UPD

If you want to do it on initialization you may use ... (spread) operator:

const a = {
    android: {
        time: 1,
        diff: 2
   }
};

let b = {
    out:{
       x: null,
       context:{
           state: null,
           value: null,
           time: 3,
           diff: 4,
           ...a.android
       }
    }
 };
 

console.log(b);
Makarov Sergey
  • 932
  • 7
  • 21