반응형
두 json 개체를 jquery와 병합
나는 두 개의 json 객체가 있습니다.
http://example.com/search.json?section=saloon
그리고.
http://example.com/search.json?section=coupe
저는 이 두 물체를 하나의 물체로 결합하는 방법을 찾고 있었습니다.
잘 부탁드립니다.
쓰임
var object = $.extend({}, object1, object2);
빈 개체를 대상(첫 번째) 인수로 전달하여 두 번째 개체를 병합하려면 두 개체를 모두 보존할 수 있습니다.
$.extend(object1, object2);
JSON을 가져오고 구문 분석한 후 속성을 반복하여 새 개체에 추가할 수 있습니다.그러나 이름이 같은 속성이 있으면 덮어쓰게 되므로 주의하십시오.
var data1 = '{"foo": 123, "test":"foo"}';
var data2 = '{"bar": 456, "test":"bar"}';
var json1 = JSON.parse(data1);
var json2 = JSON.parse(data2);
var merged = {};
for(var i in json1) {
if (json1.hasOwnProperty(i))
merged[i] = json1[i];
}
for(var i in json2) {
if (json2.hasOwnProperty(i))
merged[i] = json2[i];
}
console.log(merged);
병합된 JSON 개체의 결과는 다음과 같습니다.
{foo: 123, test: "bar", bar: 456}
편집: 3nigma가 언급했듯이, 만약 당신이 jQuery를 사용한다면, 당신은 더 잘 사용할 수 있습니다.기존 개체를 수정하지 않으려면 먼저 빈 개체를 전달하는 것을 잊지 마십시오.
병합을 사용할 수 있습니다.
var mergedObj = $.merge(jsonObj1, jsonObj2);
하나의 속성이 다르더라도 전체 개체를 덮어씁니다. 새 속성으로 개체를 추가하고 JSON의 리프만 덮어쓰려면 이 모든 것을 사용합니다.
//smart not to delete entire object if a property is different, (unlike $.extend or _.extend)
// {"a":{"b":"c", "e":"f"}},{"a":{"b":"x"}} -> {"a":{"b":"x", "e":"f"}} not {"a":{"b":"x"}}
//obj1 is not effected,
//obj1 values are overwriten at leaves of obj2
// smartJSONextend({"a":{"b":"c"}},{"a":"d"}) - {"b":"c"} will be "d"
function smartJSONextend(obj1, obj2) {
//clone
var mergedObj = JSON.parse(JSON.stringify(obj1));
(function recurse(currMergedObj, currObj2){
var key;
for (key in currObj2) {
if (currObj2.hasOwnProperty( key )){
//keep path alive in mergedObj
if (!currMergedObj[key]){
currMergedObj[key] = undefined;
}
if ( typeof currObj2[key] === "string" || typeof currObj2[key] === "number" || typeof currObj2[key] === "boolean" ){
//overwrite if obj2 is leaf and not nested
currMergedObj[key] = currObj2[key];
} else if (typeof currObj2[key] === "object"){
//obj2 is nested
//and currMergedObj[key] is undefined, sync types
if (!currMergedObj[key]) {
//obj2[key] ifArray
if(currObj2[key].length !== undefined){
currMergedObj[key] = [];
} else {
currMergedObj[key] = {};
}
}
recurse(currMergedObj[key], currObj2[key]);
}
}
}
}(mergedObj, obj2));
return mergedObj;
}
라페이 덕분에.
하나의 개체를 배열로 확장하려면 완전히 작동합니다. 예를 들어 다음과 같습니다.
$(document).ready(function() {
$(document).on("click", ".btnClassClose", function () {
var tinyMCEcontent = tinymce.activeEditor.getContent();
var getAttrIDArray = [];
$("#" + getelementId).html("");
$("#" + getelementId).html(tinyMCEcontent);
$("#" + getelementId).append(buttonEDI);
var PageName = new Object();
PageName["mdlPageContentHtml"] = tinyMCEcontent;
var getarraylist = JSON.parse($("#" + getelementId).attr('data-atrrib'));
var obj = $.extend({}, getarraylist, PageName);
getAttrIDArray.push(obj);
var contentGetAttrIDArray = SecondMainSendAjax("CMS?handler=Content", getAttrIDArray);
});
});
언급URL : https://stackoverflow.com/questions/8478260/merge-two-json-objects-with-jquery
반응형
'it-source' 카테고리의 다른 글
VS Code에서 통합 터미널을 별도의 창에서 열 수 있습니까? (0) | 2023.08.09 |
---|---|
java.lang을 가져오는 중입니다.REST Assured를 사용하여 테스트할 때 AbstractMethodError가 발생함 (0) | 2023.08.09 |
jQuery에서 클릭 앤 홀드를 청취하려면 어떻게 해야 합니까? (0) | 2023.08.09 |
PowerShell: 로컬 사용자 계정 만들기 (0) | 2023.08.09 |
PostgreSQL - 따옴표 없이 구문 쿼리 (0) | 2023.08.09 |