programing

2개의 json/javascript 어레이를 1개의 어레이로 Marge합니다.

css3 2023. 3. 6. 21:20

2개의 json/javascript 어레이를 1개의 어레이로 Marge합니다.

다음과 같은 2개의 json 어레이가 있습니다.

var json1 = [{id:1, name: 'xxx' ...}]
var json2 = [{id:2, name: 'xyz' ...}]

단일 어레이에 통합하고 싶다.

var finalObj = [{id:1, name: 'xxx' ...},{id:2, name: 'xyz' ...}]

방법을 원하는군요.

var finalObj = json1.concat(json2);

처음 등장했을 때 "merg"라는 단어는 JSON 개체를 "머지"하기 위한 적절한 jQuery 방법인 .extend를 사용해야 한다고 생각하게 합니다.하지만,$.extend(true, {}, json1, json2);는, 같은 키명을 공유하는 모든 값을, 파라메스로 지정된 최신의 값에 의해서 덮어씁니다.질문의 리뷰에서 알 수 있듯이 이는 바람직하지 않습니다.

당신이 찾는 것은 .concat으로 알려진 단순한 javascript 함수입니다.다음과 같이 동작합니다.

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>

jsFiddle

Marge를 시도할 수 있습니다.

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]

es6을 사용하는 경우 새 js 스프레드 연산자를 사용할 수 있습니다.

var json1 = [{id:1, name: 'xxx'}]
var json2 = [{id:2, name: 'xyz'}]
var finalObj = [...json1, ...json2]

console.log(finalObj)

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>

jQuery 확장 메서드를 사용하여 다음 코드를 사용해 보십시오.

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