0
假設我有兩個json對象,我需要合併它們。將json對象與數組合並
css: [{
drag: "mode() == 'layout'",
ui_draggable: "mode() == 'layout'"
}]
css: [{
someclass : true
}]
我想結束了:
css: [{
drag: "mode() == 'layout'",
ui_draggable: "mode() == 'layout'",
someclass : true
}]
一些進一步審理中我想出了這個之後,但我認爲我有地方一些錯誤或它的代碼無用行。
我稍微玩了一段代碼就想出了這段代碼。我的需求不需要遞減兩個以上的級別,所以這很好。我相信它可能會有很大的改進,但它對綁定淘汰賽非常有用。下面是我如何使用它來擴展jQuery的不顯眼knockoutjs
var settings = {
text: 'SelectedCard().CardData.Title',
visible: "mode() != 'edit' || !isMyCard()",
css: [{ drag: "mode() == 'layout'" , selectedElement: "selectedCardElement() == '_titlePreview'"}]
};
var settings2 =
{
css: [{ drag: "mode() == 'layout'"}]
};
var settings3 = merge(settings, settings2);
function merge(first, second) {
for (var a1 in first) {
// if second object is null we are finished.
used.push(a1);
if (second[a1] == null) {
continue;
} else {
var ob2 = second[a1];
if (typeof (first[a1]) != typeof (ob2)) {
throw new Error("conflicting properties named:" + a1);
}
if ($.isArray(first[a1])) {
for (var i = 0; i < ob2.length; i++) {
first[a1].push(ob2[i]);
}
} else {
// matching property.
return merge(first[a1], second[a1]);
}
}
}
for (var a2 in second) {
if (used.indexOf(a2) < 0) {
first[a2] = second[a2];
}
}
return first;
}
這些不是「JSON對象」。 JSON是一個字符串。這些是物體。 –
https://www.google.com/search?q=javascript+objects+merge SO不是您的[個人研究助理](http://meta.stackexchange.com/a/128553/165612)。 – iambriansreed
Exact Duplicate:http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically – iambriansreed