2개의 JSON 개체를 연결합니다.
저는 같은 구조의 JSON 오브젝트를 2개 가지고 있는데 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' }
실제 방법은 JS Object.assign을 사용하는 것입니다.
Object.assign(target, ...sources)
ES7에 대해 제안되고 Babel 플러그인과 함께 사용할 수 있는 다른 개체 확산 연산자가 있습니다.
 Obj = {...sourceObj1, ...sourceObj2}
사용방법:
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 }
여기서부터.
jquery 확장 방법을 사용할 수 있습니다.
예:
o1 = {"foo":"bar", "data":{"id":"1"}};
o2 = {"x":"y"};
sum = $.extend(o1, o2);
결과:
sum = {"foo":"bar", "data":{"id":"1"}, "x":"y"}
한 가지 솔루션은 목록/어레이를 사용하는 것입니다.
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}
]
TypeScript 를 사용하고 있는 경우는, 확산 연산자를 사용할 수 있습니다(...)
var json = {...json1,...json2} 
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 }
좋아, 한 줄의 코드로 할 수 있어이 경우 json2.2011이 필요합니다(이미 필요).여기에 있는 2개의 json 객체는 파싱되지 않은 문자열입니다.
json1 = '[{"foo":"bar"},{"bar":"foo"},{"name":"craig"}]';
json2 = '[{"foo":"baz"},{"bar":"fob"},{"name":"george"}]';
concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));
밑줄로 한번 써보세요.
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);
결과
var baseArrayOfJsonObjects = [{},{}];
for (var i=0; i<arrayOfJsonObjectsFromAjax.length; i++) {
    baseArrayOfJsonObjects.push(arrayOfJsonObjectsFromAjax[i]);
}
사용방법:
let jsonFile = {};    
let schemaJson = {};    
schemaJson["properties"] = {};    
schemaJson["properties"]["key"] = "value";
jsonFile.concat(schemaJson);
가장 간단한 방법:
const json1 = { value1: '1', value2: '2' };
const json2 = { value2: '4', value3: '3' };
const combinedData = {
  json1,
  json2
};
console.log(combinedData)
네가 이걸 원하는지 모르겠어:
어레이에서 작성하기 위해 이 기능을 사용할 수 있습니다.모든 어레이에는 동일한 수의 엘리먼트가 포함되어 있습니다.
예:다음과 같은 경우:
let a = ["a", "b", "c"];
let b = [1, 2, 3];
사용하다
concatArraysLikeJson([a, b]);
결과는 다음과 같습니다.
let result = {
 0 : ["a", 1],
 1 : ["b", 2],
 2 : ["c", 3]
};
타이프 스크립트
concatArraysLikeJson(arrays:any){
 let result:any = {};
 let size:number = 0;
 let make:boolean = true;
 if(arrays.length > 0){
  size = arrays[0].length;
  for(let i = 1; i < arrays.length; i++){
    let array = arrays[i];
    
    if(make){
      if(array.length != size){
        make = false;
      }
    }
  }
 }
 if(make){
  for (let o = 0; o < size; o++) {
    result[o] = [];
  }
  for(let i = 0; i < arrays.length; i++){
    const array = arrays[i];
    //console.log(array);
    for (let o = 0; o < size; o++) {
      const element = array[o];
      result[o].push(element);
    }
  }
  return result;
 }else{
  return false;
 }
}
Javascript:
concatArraysLikeJson(arrays){
 let result = {};
 let size = 0;
 let make = true;
 if(arrays.length > 0){
  size = arrays[0].length;
  for(let i = 1; i < arrays.length; i++){
    let array = arrays[i];
    
    if(make){
      if(array.length != size){
        make = false;
      }
    }
  }
}
if(make){
  for (let o = 0; o < size; o++) {
    result[o] = [];
  }
  for(let i = 0; i < arrays.length; i++){
    const array = arrays[i];
    //console.log(array);
    for (let o = 0; o < size; o++) {
      const element = array[o];
      result[o].push(element);
    }
  }
  return result;
}else{
  return false;
}
  }
JSON 오브젝트와 어레이는 구조 내에서 여러 방법으로 조합할 수 있습니다.
json-object-merge를 사용하여 json을 규칙과 병합할 수 있습니다.
import JSONObjectMerge from "json-object-merge";
const target = {
  store: {
    book: [
      {
        category: "reference",
        author: "Nigel Rees",
        title: "Sayings of the Century",
        price: 8.95
      }
    ],
    bicycle: {
      color: "red",
      price: 19.95
    }
  }
};
const source = {
  store: {
    book: [
      {
        category: "fiction",
        author: "Evelyn Waugh",
        title: "Sword of Honour",
        isbn: "0-679-43136-5",
        price: 12.99
      }
    ]
  }
};
const merged = JSONObjectMerge(target, source, { "$.store.book": "PREPEND" });
expect(merged).toEqual({
  store: {
    book: [
      {
        // books from source are prepended to the original array
        category: "fiction",
        author: "Evelyn Waugh",
        title: "Sword of Honour",
        isbn: "0-679-43136-5",
        price: 12.99
      },
      {
        category: "reference",
        author: "Nigel Rees",
        title: "Sayings of the Century",
        price: 8.95
      }
    ],
    bicycle: {
      color: "red",
      price: 19.95
    }
  }
});
언급URL : https://stackoverflow.com/questions/433627/concatenate-two-json-objects
'sourcecode' 카테고리의 다른 글
| material-ui TextField, DropDownMenu 컴포넌트에서 데이터를 가져오려면 어떻게 해야 합니까? (0) | 2023.04.04 | 
|---|---|
| 형식 스크립트 속성이 유니언 유형에 없습니다. (0) | 2023.04.04 | 
| Woocommerce 제품의 할인된 가격과 백분율을 표시합니다. (0) | 2023.04.04 | 
| WooCommerce - 제품 페이지 외부에 카트 항목 이름 나열 (0) | 2023.04.04 | 
| 대응 - 로그인 및 인증을 처리하는 가장 좋은 방법은 무엇입니까? (0) | 2023.04.04 |