gpt4 book ai didi

javascript - 如何在不覆盖值的情况下合并javascript中的对象

转载 作者:数据小太阳 更新时间:2023-10-29 06:11:46 26 4
gpt4 key购买 nike

如何将对象中的重复键合并到一个对象中并连接对象中的值我有这样的对象

var object1 = {
role: "os_and_type",
value: "windows"
};
var object2 = {
role: "os_and_type",
value: "Android"
};
var object3 = {
role: "features",
value: "GSM"
};

我怎样才能实现这个目标

new_object = [{
role: "os_and_type",
value: ["windows", "android"]
}, {
role: "features",
value: ["GSM"]
}];

最佳答案

给你:

var object1 = {
role: "os_and_type",
value: "windows"
};
var object2 = {
role: "os_and_type",
value: "Android"
};
var object3 = {
role: "features",
value: "GSM"
};

function convert_objects(){
var output = [];
var temp = [];
for(var i = 0; i < arguments.length; i++){ // Loop through all passed arguments (Objects, in this case)
var obj = arguments[i]; // Save the current object to a temporary variable.
if(obj.role && obj.value){ // If the object has a role and a value property
if(temp.indexOf(obj.role) === -1){ // If the current object's role hasn't been seen before
temp.push(obj.role); // Save the index for the current role
output.push({ // push a new object to the output,
'role':obj.role,
'value':[obj.value] // but change the value from a string to a array.
});
}else{ // If the current role has been seen before
output[temp.indexOf(obj.role)].value.push(obj.value); // Save add the value to the array at the proper index
}
}
}
return output;
}

这样调用它:

convert_objects(object1, object2, object3);

您可以根据需要向函数添加任意数量的对象。

关于javascript - 如何在不覆盖值的情况下合并javascript中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21495610/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com