1

I have individual objects like:

Object {au: Object}
Object {eu: Object}
Object {fr: Object}

etc

How do I combine them so they look like this:

Object {au: Object, eu: Object, fr: Object, uk: Object, us: Object} 

I have the data in a for loop like so:

 for(var i = 0; i < storesListArray.length; ++i) {
     var storeListArray = storesListArray[i];
     for(var j = 0; j < storeListArray.length; ++j) {
         console.log(storeListArray[j]);
     }
 }

Any help one the best way would be awesome thank you.

JJJ
  • 32,902
  • 20
  • 89
  • 102
user2200113
  • 55
  • 1
  • 5
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign – Meirion Hughes Apr 06 '17 at 19:19
  • 2
    Possible duplicate of [How to concatenate properties from multiple JavaScript objects](http://stackoverflow.com/questions/2454295/how-to-concatenate-properties-from-multiple-javascript-objects) – JJJ Apr 06 '17 at 19:20

4 Answers4

10

You could use Object.assign and spread syntax ... for getting a single object with the parts of the array.

var array = [{ au: {} }, { eu: {} }, { fr: {} }],
    object = Object.assign({}, ...array);

console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

Another way

var list = [
 {en: {a: "something", b: "something else"}},
 {fr: {a: "something", b: "something else"}},
 {au: {a: "something", b: "something else"}}
]

var bigObj = list.reduce(function (o, n) {
  for (var key in n) o[key] = n[key];
  return o;
}, {});

console.log(bigObj);
James
  • 20,957
  • 5
  • 26
  • 41
-1

You can use jQuery.extend to merge several objects into one. The first parameter is the target object and the following parameters are the ones you want to add to the target:

 var oAll = $.extend({},objA, objB, objC ... )
Daniel AG
  • 320
  • 1
  • 9
-1

I would begin by using the Array.prototype.forEach to iterate over the elements of the array.

If you're willing to use jQuery, the jQuery.extend can be very useful in copying objects.

var storesListArray = [
 {en: {a: "something", b: "something else"}},
 {fr: {a: "something", b: "something else"}},
 {au: {a: "something", b: "something else"}}
]

var ans = {};
storesListArray.forEach(function(element){
  $.extend(true, ans, element);
 })

console.log(ans);

console.log("en:");
console.log(ans.en);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hodrobond
  • 1,665
  • 17
  • 18
  • I get Object {0: Object, 1: Object, 2: Object, 3: Object, 4: Object, 5: Object} I need the keys to be the codes – user2200113 Apr 06 '17 at 19:27
  • "keys to be the codes", as in `ans.en` should return the object with keys `a` and `b`? – Hodrobond Apr 06 '17 at 19:29
  • var storeMapping = {}; storesListArray.forEach(function(element){ element.forEach(function(key){ jQuery.extend(true, storeMapping, key); }); }); – user2200113 Apr 06 '17 at 19:35