programing

중첩된 JSON: 개체에 새 항목을 추가하는 방법(푸시)

goodjava 2023. 3. 16. 21:28

중첩된 JSON: 개체에 새 항목을 추가하는 방법(푸시)

어레이, 오브젝트 및 JSON부터 시작하는데, 여기서 간과하고 있는 것이 있습니다.새 항목을 json 개체에 추가(푸시)하려고 할 때 오류가 발생했습니다.

다음 오류가 발생하였습니다.Result of expression 'library.push' [undefined] is not a function (내 코드 스니펫 하단에 표시)

// This is my JSON object generated from a database
var library = {
    "Gold Rush" : {
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["1.jpg","","2.jpg"]
    },
    "California" : {
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["3.jpg","4.jpg","5.jpg"]
    }
}

// These will be dynamically generated vars from editor
var title = "Gold Rush";
var foregrounds = ["Howdy","Slide 2"];
var backgrounds = ["1.jpg",""];

function save () {

    // If title already exists, modify item
    if (library[title]) {
        // Replace values with new
        library[title].foregrounds = foregrounds;
        library[title].backgrounds = backgrounds;

        // Save to Database. Then on callback...
        document.write('Changes Saved to <b>'+title+'</b>');

    // If title does not exist, add new item
    else {
        // Format it for the JSON object
        var item = ('"'+title+'" : {"foregrounds" : '+foregrounds+',"backgrounds" : '+backgrounds+'}');


        // THE PROBLEM SEEMS TO BE HERE??
        // Error: "Result of expression 'library.push' [undefined] is not a function"
        library.push(item);


        // Save to Database. Then on callback...
        document.write('Added: <b>'+title+'</b>');
    }
}

save();

library는 객체이지 배열이 아닙니다.어레이에 푸시할 수 있습니다.PHP와 달리 Javascript는 구별을 합니다.

코드는 키-값 쌍의 소스 코드와 같은 문자열을 만든 다음 개체에 "푸시"하려고 합니다.그건 작동 방식과는 거리가 멀어요.

새로운 키와 값의 쌍을 오브젝트에 추가합니다.여기서 키는 제목이고 값은 다른 오브젝트입니다.이것은 다음과 같습니다.

library[title] = {"foregrounds" : foregrounds, "backgrounds" : backgrounds};

"JSON 객체"는 애매한 용어입니다.프로그램 내 메모리 내의 실제 개체와 JSON 형식의 텍스트 조각을 구별하도록 주의해야 합니다.

키가 없는 JSON은 다음과 같이 실행할 수 있습니다.

library[library.length] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};

자, 이걸 써보세요.

var library = {[{
    "title"       : "Gold Rush",
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["1.jpg","","2.jpg"]
    }, {
    "title"       : California",
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["3.jpg","4.jpg","5.jpg"]
    }]
}

그 후, 다음과 같이 입력합니다.

library[library.length] = {"title" : "Gold Rush", "foregrounds" : ["Howdy","Slide 2"], "backgrounds" : ["1.jpg",""]};

push는 Array 메서드입니다.json 객체의 경우 정의할 필요가 있습니다.

이것으로 충분합니다.

library[title] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};

Lodash 함수를 사용하여 이를 달성할 수 있습니다.

library[title] = _.assign({}, {'foregrounds': foregrounds }, {'backgrounds': backgrounds });

// This is my JSON object generated from a database
var library = {
  "Gold Rush": {
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],
    "backgrounds": ["1.jpg", "", "2.jpg"]
  },
  "California": {
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],
    "backgrounds": ["3.jpg", "4.jpg", "5.jpg"]
  }
}

// These will be dynamically generated vars from editor
var title = "Gold Rush";
var foregrounds = ["Howdy", "Slide 2"];
var backgrounds = ["1.jpg", ""];

function save() {

  // If title already exists, modify item
  if (library[title]) {

    // override one Object with the values of another (lodash)
    library[title] = _.assign({}, {
      'foregrounds': foregrounds
    }, {
      'backgrounds': backgrounds
    });
    console.log(library[title]);

    // Save to Database. Then on callback...
    // console.log('Changes Saved to <b>' + title + '</b>');
  }

  // If title does not exist, add new item
  else {
    // Format it for the JSON object
    var item = ('"' + title + '" : {"foregrounds" : ' + foregrounds + ',"backgrounds" : ' + backgrounds + '}');

    // THE PROBLEM SEEMS TO BE HERE??
    // Error: "Result of expression 'library.push' [undefined] is not a function"
    library.push(item);

    // Save to Database. Then on callback...
    console.log('Added: <b>' + title + '</b>');
  }
}

save();
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

언급URL : https://stackoverflow.com/questions/6503193/nested-json-how-to-add-push-new-items-to-an-object