두 개의 json / javascript 배열을 하나의 배열로 병합
두 개의 json 배열이 있습니다.
var json1 = [{id:1, name: 'xxx' ...}]
var json2 = [{id:2, name: 'xyz' ...}]
단일 배열로 병합하고 싶습니다.
var finalObj = [{id:1, name: 'xxx' ...},{id:2, name: 'xyz' ...}]
문안 인사
당신은 concat
방법을 원합니다 .
var finalObj = json1.concat(json2);
처음 등장했을 때 "merg"라는 단어 는 JSON 객체를 "병합"하는 적절한 jQuery 방식 인 .extend 를 사용해야한다고 생각 하게합니다. 그러나 $.extend(true, {}, json1, json2);
동일한 키 이름을 공유하는 모든 값이 params에 제공된 최신 값으로 재정의됩니다. 귀하의 질문에 대한 검토에서 알 수 있듯이 이것은 바람직하지 않습니다.
당신이 찾는 것은 .concat으로 알려진 간단한 자바 스크립트 함수 입니다. 다음과 같이 작동합니다.
var finalObj = json1.concat(json2);
이것은 기본 jQuery 함수는 아니지만 다음과 같이 간단하게 나중에 사용할 수 있도록 jQuery 라이브러리에 쉽게 추가 할 수 있습니다.
;(function($) {
if (!$.concat) {
$.extend({
concat: function() {
return Array.prototype.concat.apply([], arguments);
}
});
}
})(jQuery);
그런 다음 다음과 같이 원하는대로 호출합니다.
var finalObj = $.concat(json1, json2);
이 유형의 여러 배열 객체에 다음과 같이 사용할 수도 있습니다.
var finalObj = $.concat(json1, json2, json3, json4, json5, ....);
그리고 정말로 원한다면 jQuery 스타일과 매우 짧고 달콤한 (일명 축소)
;(function(a){a.concat||a.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);
;(function($){$.concat||$.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);
$(function() {
var json1 = [{id:1, name: 'xxx'}],
json2 = [{id:2, name: 'xyz'}],
json3 = [{id:3, name: 'xyy'}],
json4 = [{id:4, name: 'xzy'}],
json5 = [{id:5, name: 'zxy'}];
console.log(Array(10).join('-')+'(json1, json2, json3)'+Array(10).join('-'));
console.log($.concat(json1, json2, json3));
console.log(Array(10).join('-')+'(json1, json2, json3, json4, json5)'+Array(10).join('-'));
console.log($.concat(json1, json2, json3, json4, json5));
console.log(Array(10).join('-')+'(json4, json1, json2, json5)'+Array(10).join('-'));
console.log($.concat(json4, json1, json2, json5));
});
center { padding: 3em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<center>See Console Log</center>
병합을 시도 할 수 있습니다.
var finalObj = $.merge(json1, json2);
jQuery를 사용하고 있기 때문입니다. jQuery.extend () 메서드는 어떻습니까?
http://api.jquery.com/jQuery.extend/
설명 : 두 개 이상의 개체의 내용을 첫 번째 개체로 병합합니다.
Es 6의 새로운 기능을 사용하여이 작업을 수행 할 수 있습니다.
var json1 = [{id:1, name: 'xxx' , ocupation : 'Doctor' }];
var json2 = [{id:2, name: 'xyz' ,ocupation : 'SE'}];
var combineJsonArray = [...json1 , ...json2];
//output should like this [ { id: 1, name: 'xxx', ocupation: 'Doctor' },
{ id: 2, name: 'xyz', ocupation: 'SE' } ]
또는 두 개의 json 배열 사이에 추가 문자열이나 다른 것을 넣을 수 있습니다.
var json3 = [...json1 ,"test", ...json2];
// output should like this : [ { id: 1, name: 'xxx', ocupation: 'Doctor' },
'test',
{ id: 2, name: 'xyz', ocupation: 'SE' } ]
아마도 javascript의 배열 구문을 사용할 수 있습니다.
var finalObj =[json1 , json2]
Lodash _.merge
기능을 사용하여 이를 달성 할 수 있습니다 .
var json1 = [{id:1, name: 'xxx'}];
var json2 = [{id:2, name: 'xyz'}];
var merged = _.merge(_.keyBy(json1, 'id'), _.keyBy(json2, 'id'));
var finalObj = _.values(merged);
console.log(finalObj);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
es6를 사용하는 경우 새 js 확산 연산자를 사용할 수 있습니다.
var json1 = [{id:1, name: 'xxx'}]
var json2 = [{id:2, name: 'xyz'}]
var finalObj = [...json1, ...json2]
console.log(finalObj)
jQuery extend 메소드를 사용하여 아래 코드를 시도하십시오.
var json1 = {"name":"ramesh","age":"12"};
var json2 = {"member":"true"};
document.write(JSON.stringify($.extend(true,{},json1,json2)))
var json1=["Chennai","Bangalore"];
var json2=["TamilNadu","Karanataka"];
finaljson=json1.concat(json2);
참고 URL : https://stackoverflow.com/questions/10384845/merge-two-json-javascript-arrays-in-to-one-array
'developer tip' 카테고리의 다른 글
NotificationChannel에서 사운드 비활성화 (0) | 2020.11.13 |
---|---|
MySQL-한 쿼리에서 테이블 당 모든 행을 계산하는 방법 (0) | 2020.11.13 |
Django 뷰에서 HTTP 상태 코드 204를 반환하려면 어떻게해야합니까? (0) | 2020.11.13 |
Bootstrap의 축소 열기 / 닫기 애니메이션 비활성화 (0) | 2020.11.13 |
배포 인증서가 만료되면 어떻게됩니까? (0) | 2020.11.13 |