var a=[{"id":1,"total":1000},{"id":2,"total":2000}]
var b=[{"id":1,"credit":500},{"id":2,"credit":1000}]
var c=[{"id":1,"reversed":500},{"id":2,"amount":1000}]
我想要这样的东西,
var newArray=[{"id":1,
"amount":
{"total":1000,"credit":500,"reversed":500}}
{"id":2,
"amount":
{"total":2000,"credit":1000,"reversed":1000}}
]
是否可以通过JavaScript函数实现此目的?
答案 0 :(得分:0)
var a=[{"id":1,"total":1000},{"id":2,"total":2000}];
var b=[{"id":1,"credit":500},{"id":2,"credit":1000}];
var c=[{"id":1,"reversed":500},{"id":2,"amount":1000}];
var result = $.extend(true, {}, a, b,c);
var newArray = [];
$.each(result,function(index,value){
var ind = value.id;
delete value['id']; //unset id here
var amount = value;
newArray.push({id: ind,amount:amount});
});
console.log(newArray);

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:0)
您可以使用哈希表作为对具有相同id
的对象的引用。迭代所有数组并使用子数组获取键并将值赋给引用的对象。
使用的方法:
Array#forEach
,迭代数组
Object.keys
,用于获取对象的所有密钥。
var array1 = [{ "id": 1, "total": 1000 }, { "id": 2, "total": 2000 }],
array2 = [{ "id": 1, "credit": 500 }, { "id": 2, "credit": 1000 }],
array3 = [{ "id": 1, "reversed": 500 }, { "id": 2, "amount": 1000 }],
hash = Object.create(null),
result = [];
[array1, array2, array3].forEach(function (a) {
a.forEach(function (o) {
if (!hash[o.id]) {
hash[o.id] = {};
result.push(hash[o.id]);
}
Object.keys(o).forEach(function (k) {
hash[o.id][k] = o[k];
});
});
});
console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;