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.

2

4 Answers 4

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

-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>

3 Comments

I get Object {0: Object, 1: Object, 2: Object, 3: Object, 4: Object, 5: Object} I need the keys to be the codes
"keys to be the codes", as in ans.en should return the object with keys a and b?
var storeMapping = {}; storesListArray.forEach(function(element){ element.forEach(function(key){ jQuery.extend(true, storeMapping, key); }); });
-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 ... )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.