合并JavaScript对象与相同的密钥阵列 [英] Merge javascript objects in array with same key

查看:257
本文介绍了合并JavaScript对象与相同的密钥阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是重组最好的办法阵列输出?我需要合并所有值的键(是否阵与否)为对象共享相同的名称密钥。有类似<一个href=\"http://stackoverflow.com/questions/24076487/combining-javacript-objects-in-array-with-same-key-value\">here,但是,这并不回答我的问题,因为我有数组为好。

What is the best way to reorganize array into output? I need to merge all value keys (whether array or not) into objects sharing the same name key. There is something similar here, but that doesn't answer my question because I have arrays as well.

var array = [{name:"foo1",value:"val1"},{name:"foo1",value:["val2","val3"]},{name:"foo2",value:"val4"}];

var output = [{name:"foo1",value:["val1","val2","val3"]},{name:"foo2",value:["val4"]}];

是的,我可以写无尽中的循环和几个阵列,但有一个简单的(R)快捷方式?谢谢!

Yes, I can write endless for loops and several arrays in between, but is there a simple(r) shortcut? Thanks!

推荐答案

不知道如果theres更好/更简单的方法,但是这将做到这一点: -

Not sure if theres a better/easier way, but this would do it:-

var array = [{name:"foo1",value:"val1"},{name:"foo1",value:["val2","val3"]},{name:"foo2",value:"val4"}];

var output = [];

array.forEach(function(value) { 
    var existing = output.filter(function(v, i) { 
        return v.name == value.name; 
    }); 
    if(existing.length) {
        var existingIndex = output.indexOf(existing[0]);
        output[existingIndex].value = output[existingIndex].value.concat(value.value); 
    }
    else {
        if(typeof value.value == 'string')
            value.value = [value.value];
        output.push(value);  
    }
});

console.dir(output);

这篇关于合并JavaScript对象与相同的密钥阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆