0
var collection = {
    "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"
    }
};

var collectionCopy = JSON.parse(JSON.stringify(collection));

function updateRecords(id, prop, value) {  
  if (!value) delete collection[id][prop];
  if (!!value && prop === 'tracks'){

   collection[id][prop] = []; // Solve my problem

    collection[id][prop].push(value);
  } 
  if (!!value && prop === 'artist') collection[id][prop] = value;
  return collection;
}

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

This is original code that return an error. This is an edited and please ignore this question thanks. Trying to fix the error saying push is undefined function. You can't push an value on array object if Undefined so I put the

collection[id][prop] = []; // Solve my problem

to avoid getting error saying push is undefined on this line of code....

collection[id][prop].push(value);

3
  • collection["5439"]["tracks"] = ['Something']? Commented Jun 22, 2016 at 13:08
  • 1
    Also this is not nested arrays, its an object. Commented Jun 22, 2016 at 13:09
  • This is the problem = "If prop does contain the key "tracks" and its value is non-blank, then push the value onto the end of its existing tracks array." Commented Jun 22, 2016 at 13:13

2 Answers 2

3

Try following

collection["5439"].tracks = ["some info", "some more info"];
Sign up to request clarification or add additional context in comments.

Comments

0

You have an object collection and in order to access/ update the object you can use either . or [] notations. In order to use . notation, the key need to be a valid identifier. The number identifier "5439" is not a valid identifier and will give a SyntaxError. The safe way of doing this is using the [] notation as below:

collection["5439"]["tracks"] = [1, 2, 3, "a", "b"];

2 Comments

Thank you guys, my problem was solve, This is something to do with push() function is undefined. You can't use push() on undefined array
Original Task = "If prop does contain the key "tracks" and its value is non-blank, then push the value onto the end of its existing tracks array."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.