Program Tip

두 개의 JSON 객체 연결

programtip 2020. 11. 19. 21:53
반응형

두 개의 JSON 객체 연결


동일한 구조를 가진 두 개의 JSON 개체가 있으며 Javascript를 사용하여 함께 연결하고 싶습니다. 이 작업을 수행하는 쉬운 방법이 있습니까?


주석의 설명에 따라 배열 연결을 수행하면됩니다.

var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}];
var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
jsonArray1 = jsonArray1.concat(jsonArray2);
// jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}, 
//{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];

속성을 복사하려는 경우 :

var json1 = { value1: '1', value2: '2' };
var json2 = { value2: '4', value3: '3' };


function jsonConcat(o1, o2) {
 for (var key in o2) {
  o1[key] = o2[key];
 }
 return o1;
}

var output = {};
output = jsonConcat(output, json1);
output = jsonConcat(output, json2);

위 코드의 출력은{ value1: '1', value2: '4', value3: '3' }


jquery extend 메소드를 사용할 수 있습니다 .

예:

o1 = {"foo":"bar", "data":{"id":"1"}};
o2 = {"x":"y"};
sum = $.extend(o1, o2);

결과:

sum = {"foo":"bar", "data":{"id":"1"}, "x":"y"}

실제 방법은 JS Object.assign을 사용하는 것입니다.

Object.assign(target, ...sources)

MDN 링크

ES7 용으로 제안되고 Babel 플러그인과 함께 사용할 수있는 또 다른 객체 확산 연산자가 있습니다.

 Obj = {...sourceObj1, ...sourceObj2}

한 가지 해결책은 목록 / 배열을 사용하는 것입니다.

var first_json = {"name":"joe", "age":27};
var second_json = {"name":"james", "age":32};

var jsons = new Array();
jsons.push(first_json);
jsons.push(second_json);

결과

jsons = [
    {"name":"joe", "age":27},
    {"name":"james", "age":32}
]

Object.assign () 메서드를 사용할 수 있습니다 . Object.assign () 메서드는 하나 이상의 소스 객체에서 대상 객체로 열거 가능한 모든 속성 값을 복사하는 데 사용됩니다. 대상 개체를 반환합니다. [1]

var o1 = { a: 1 }, o2 = { b: 2 }, o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }

나는 사용한다

let x = { a: 1, b: 2, c: 3 }

let y = {c: 4, d: 5, e: 6 }

let z = Object.assign(x, y)

console.log(z)

// OUTPUTS:

{ a:1, b:2, c:4, d:5, e:6 }

https://www.quora.com/How-can-I-add-two-JSON-objects-into-one-object-JavaScript


okay, you can do this in one line of code. you'll need json2.js for this (you probably already have.). the two json objects here are unparsed strings.

json1 = '[{"foo":"bar"},{"bar":"foo"},{"name":"craig"}]';

json2 = '[{"foo":"baz"},{"bar":"fob"},{"name":"george"}]';

concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));

Just try this, using underscore

var json1 = [{ value1: '1', value2: '2' },{ value1: '3', value2: '4' }];
var json2 = [{ value3: 'a', value4: 'b' },{ value3: 'c', value4: 'd' }];
var resultArray = [];
json1.forEach(function(obj, index){
  resultArray.push(_.extend(obj,  json2[index]));
});

console.log("Result Array", resultArray);

Result


if using TypeScript, you can use the spread operator (...)

var json = {...json1,...json2} 


var baseArrayOfJsonObjects = [{},{}];
for (var i=0; i<arrayOfJsonObjectsFromAjax.length; i++) {
    baseArrayOfJsonObjects.push(arrayOfJsonObjectsFromAjax[i]);
}

Only Javascript =)

var objA = { 'a': 1, 'b': 2}
var objB = { 'x': 3, 'y': 5}
objA.nameNewObj = objB

enter image description here


I use:

let jsonFile = {};    
let schemaJson = {};    
schemaJson["properties"] = {};    
schemaJson["properties"]["key"] = "value";
jsonFile.concat(schemaJson);

참고URL : https://stackoverflow.com/questions/433627/concatenate-two-json-objects

반응형