使用相同属性值的数组将多个对象合并为单个对象

时间:2016-09-22 05:04:10

标签: javascript jquery

我有五个json对象obj1,obj2,obj3,obj4和obj5,我想合并它们和crete一个json对象和obj有相同的列。结果json应该包含所有对象的所有值 问题:

var obj1 = {
    "DOP":"manu",
    "Resolution":23,
    "sensor":"SE"
}

var obj2 = {
    "DOP":"mansa",
    "Resolution":22,
    "sensor":"PS"
}

就像所有五个对象数据和结果应该只更新行而不是列,预期结果应该是

var result = {
    "Dop":["manu","mansa"],
    "Resolution":[23,25],
    "Sensor":["SE","PS"]
}

4 个答案:

答案 0 :(得分:1)

您可以使用for(x in obj)

var result = {}
for (x in obj1) { result[x] = obj1[x] + ', ' + obj2[x] }
//Object {DOP: "manu, mansa", Resolution: "23, 22", sensor: "SE, PS"}

答案 1 :(得分:0)

您想要的结果是非法的。 所有你可以拥有你的json数组。

var result = [{ "DOP":"mansa", "Resolution":22, "sensor":"PS" },
              { "DOP":"manu", "Resolution":23, "sensor":"SE" }   
             ]

答案 2 :(得分:0)

var x ={ "student-marks":{'math':1,'physics':5} }; var y ={ "student-marks":{'chemistry':3,'history':2} }; $.extend(true, {}, x, y);

我从这里得到答案:How to merge two object values by keys

答案 3 :(得分:0)

您可以在myCustomMerge()函数

中基于将无限对象作为参数合并对象

function myCustomMerge() {
    var return_obj = {};
    for (i in arguments) {
        obj = arguments[i];
        for (j in obj) {
            if (return_obj[j] == undefined) {
                return_obj[j] = [obj[j]];
            } else {
                return_obj[j].push(obj[j]);
            }
        }
    }
    return return_obj;
}


var obj1 = {
    "DOP": "manu",
    "Resolution": 23,
    "sensor": "SE"
}

var obj2 = {
    "DOP": "mansa",
    "Resolution": 22,
    "sensor": "PS",
    "special_obj2": "My Special Value"
}

var obj3 = {
    "DOP": "top",
    "Resolution": 36,
    "sensor": "ME",
    "special_obj2": "My Special Value 2"
}

var merged_obj = myCustomMerge(obj1, obj2, obj3);
console.log(merged_obj);