gpt4 book ai didi

javascript - 如何递归合并 2 个 javascript 对象?

转载 作者:行者123 更新时间:2023-11-30 08:34:38 24 4
gpt4 key购买 nike

我有 2 个对象需要合并并保持所有属性完好无损,尝试使用 jQuery $.extend 但我无法让它工作。我尝试了所有关于如何合并 javascript 对象的帖子,但就是无法让它工作。

var thz_icon_source = {"Spinners":["spinnericon1","spinnericon2"],"Awesome":["awesomeicon1","awesomeicon2"]};
var fa_icon_source = {"Spinners":["faspinner1","faspinner2"],"Awesome":["faawesome1","faawesome2"]};
var new_source ={};
$.extend(new_source,fa_icon_source,thz_icon_source);

console.log(thz_icon_source);
console.log(fa_icon_source);
console.log(new_source);

期望的输出应该是这样的

{
"Spinners":["faspinner1","faspinner2","spinnericon1","spinnericon2"],
"Awesome":["faawesome1","faawesome2","awesomeicon1","awesomeicon2"]
}

这篇文章Merge two json/javascript arrays in to one array有一个简单的对象我的和那个不一样。

最佳答案

Demo

function mergeJSON(json1,json2)
{
var result = json1 ;
for (var prop in json2)
{
if (json2.hasOwnProperty(prop))
{
result[prop] = result[prop].concat(json2[prop]);
}
}
return result;
}

关于javascript - 如何递归合并 2 个 javascript 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32792185/

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