简体   繁体   English

如何在循环中将对象组合成一个对象

[英]How to combine objects into one object in a loop

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循环中,如下所示:

 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. 最好的方法之一就是任何帮助,谢谢。

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

You could use Object.assign and spread syntax ... for getting a single object with the parts of the array. 您可以使用Object.assignspread语法...来获取包含数组部分的单个对象。

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

You can use jQuery.extend to merge several objects into one. 您可以使用jQuery.extend将多个对象合并为一个。 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 ... )

I would begin by using the Array.prototype.forEach to iterate over the elements of the array. 我将从使用Array.prototype.forEach遍历数组元素开始。

If you're willing to use jQuery, the jQuery.extend can be very useful in copying objects. 如果您愿意使用jQuery,则jQuery.extend在复制对象时会非常有用。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM