1

I have the following array:

var config = {
  default: {
    username: 'bye',
    password: '123',
    tries: 3
  },
  custom: {
    username: 'hello',
    tries: 2
  }
};

I need to get the following result from it:

var config = {
    username: 'hello',
    password: '123',
    tries: 2
};

How can I achieve this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
rossanmol
  • 1,633
  • 3
  • 17
  • 34
  • Possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – sergdenisov Feb 11 '17 at 14:35

2 Answers2

6

You can use Object.assign() to return new object.

var config = {
  default: {
    username: 'bye',
    password: '123',
    tries: 3
  },
  custom: {
    username: 'hello',
    tries: 2
  }
};

var result = Object.assign({}, config.default, config.custom)
console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • There is special function for it, surprised. thanks. – rossanmol Feb 11 '17 at 14:35
  • Note that `Object.assign` is **ES6** feature, so take care about browser compatibility [Object.assign() Browser compatibility (MDN)](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Browser_compatibility) – Mohamed Abbas Feb 11 '17 at 14:54
1

Another solution if you want to overwrite the object

Make a loop over config.custom object keys, then overwrite the keys

var config = {
  default: {
    username: 'bye',
    password: '123',
    tries: 3
  },
  custom: {
    username: 'hello',
    tries: 2
  }
};

  for (var key in config.custom) { 
    config.default[key] = config.custom[key]; 
  }

console.log(config.default);
Mohamed Abbas
  • 2,228
  • 1
  • 11
  • 19