将两个对象合并为一个对象.我有这个数组
To merge two object in to a single. I have this array
将两个对象合并为一个对象。我有这个数组
var input= [
{
code:"Abc",
a:10
},
{
code:"Abc",
a:11
},
{
code:"Abcd",
a:11
}
]
我需要输出为
[
{code:"Abc",a:[10,11]},
{code:"Abcd",a:[11]},
]
Please help
function merge(anArray){
var i, len = anArray.length, hash = {}, result = [], obj;
// build a hash/object with key equal to code
for(i = 0; i < len; i++) {
obj = anArray[i];
if (hash[obj.code]) {
// if key already exists than push a new value to an array
// you can add extra check for duplicates here
hash[obj.code].a.push(obj.a);
} else {
// otherwise create a new object under the key
hash[obj.code] = {code: obj.code, a: [obj.a]}
}
}
// convert a hash to an array
for (i in hash) {
result.push(hash[i]);
}
return result;
}
,
// UNIT TEST
var input= [
{
code:"Abc",
a:10
},
{
code:"Abc",
a:11
},
{
code:"Abcd",
a:11
}
];
var expected = [
{code:"Abc",a:[10,11]},
{code:"Abcd",a:[11]},
];
console.log("Expected to get true: ", JSON.stringify(expected) == JSON.stringify(merge(input)));
您需要合并具有相同code
的对象,因此,任务很简单:
var input = [
{
code:"Abc",
a:10
},
{
code:"Abc",
a:11
},
{
code:"Abcd",
a:11
}
];
// first of all, check at the code prop
// define a findIndexByCode Function
function findIndexByCode(code, list) {
for(var i = 0, len = list.length; i < len; i++) {
if(list[i].code === code) {
return i;
}
}
return -1;
}
var result = input.reduce(function(res, curr) {
var index = findIndexByCode(curr.code, res);
// if the index is greater than -1, the item was already added and you need to update its a property
if(index > -1) {
// update a
res[index].a.push(curr.a);
} else {
// otherwise push the whole object
curr.a = [curr.a];
res.push(curr);
}
return res;
}, []);
console.log('result', result);
相关文章:
- Javascript(Angular)从一个对象数组到第二个数组查找值
- jQuery$.inArray()总是返回-1和一个对象数组
- javascript处理一个对象数组以获得一个新的对象数组
- 我想遍历一个对象数组,我不想要任何重复项
- 尝试在一个对象的值和一个对象数组之间进行匹配
- Mongoose模式:强制创建一个对象数组
- 可以't分配给一个对象数组javascript
- 如何在Javascript或jQuery中在一个对象数组中重复值
- 使用jQuery.ajax请求向PHP函数发送一个对象数组
- 如何将所有复选框放入一个对象数组并标记选中的复选框
- 循环遍历JQueryUI选项卡控件中的每个选项卡,并构建一个对象数组
- 用javascript将一个对象数组复制到另一个数组中(深度复制)
- 给定一个对象数组,创建一个函数,该函数返回一个 Object,该 Object 具有按类型分组的路径数组
- 如何存储一个对象数组,这些对象是 ajax 查询从 javascript 中的 JSON 中提取数据的结果
- 当我将一个对象链接到一个对象数组时,两个对象的值是如何链接的
- ng-repeat失败,并显示一个对象数组
- 我可以使用 Lodash 来“折叠”一个对象数组吗?
- 根据属性值 lodash 将属性从对象数组合并到另一个对象数组中
- JavaScript检查一个对象数组的结果是错误的,而它应该是真的
- 给定一个对象数组,找到具有特定键的对象