无法使用vanilla JS将新数据添加到位于对象内的数组中

时间:2018-06-03 14:27:08

标签: javascript arrays object

我有一个名为collection的对象,其中包含名为tracks的数组,但是当我尝试使用push方法向track数组添加数据时,我收到一条错误消息。有人可以帮帮我吗。

  var collection = { .   //object with tracks property as array
        "2548": {
            "album": "Slippery When Wet",
            "artist": "Bon Jovi",
            "tracks": [
                "Let It Rock",
                "You Give Love a Bad Name"
            ]
        },
        "2468": {
            "album": "1999",
            "artist": "Prince",
            "tracks": [
                "1999",
                "Little Red Corvette"
            ]
        },
        "1245": {
            "artist": "Robert Palmer",
            "tracks": [ ]
        },
        "5439": {
            "album": "ABBA Gold"
        }
    };


    function updateRecords(id, prop, value) { 
        let addNew = collection[id].tracks;
        console.log(coll);
        if (prop == "tracks" || prop == "artist") {
            if (collection[id][prop] == undefined) {
                collection[id][prop] = value;
            }
            else if (prop == "tracks" && value != "") { //to add new value to array inside the object
                addNew.push(value);  // getting error with arr.push method
            }
        }
        return collection;
    }

    updateRecords(5439, "artist", "ABBA");  
    updateRecords(5439, "tracks", "Take a Chance on Me");
    updateRecords(5439, "tracks", "Two");

1 个答案:

答案 0 :(得分:0)

以下是如何做到的 -



var collection = { //object with tracks property as array
  "2548": {
    "album": "Slippery When Wet",
    "artist": "Bon Jovi",
    "tracks": [
      "Let It Rock",
      "You Give Love a Bad Name"
    ]
  },
  "2468": {
    "album": "1999",
    "artist": "Prince",
    "tracks": [
      "1999",
      "Little Red Corvette"
    ]
  },
  "1245": {
    "artist": "Robert Palmer",
    "tracks": []
  },
  "5439": {
    "album": "ABBA Gold"
  }
};


function updateRecords(id, prop, value) {
  let addNew = collection[id];
  if (addNew) {
      if (addNew[prop])
          collection[id][prop].push(value);
      else
          collection[id][prop] = [value];
  }
  return collection;
}

updateRecords("5439", "artist", "ABBA");
updateRecords("5439", "tracks", "Take a Chance on Me");
updateRecords("5439", "tracks", "Two");

console.log(collection);