0
votes

I am trying to push a variable into a property in a nested object, but Javascript keeps giving me this error: TypeError: Cannot read property 'push' of undefined"

However, if I declare a nested variable and use that to push, it works. Why does Javascript have this behavior?

Is there a way to do this without declaring the nested variable and without declaring an empty array?

var collection = {
    5439: {
      albumTitle: 'ABBA Gold'
    }
  };

collection[5439]["track"] = [''];
console.log(collection[5439].track);
// nested = collection[5439]["track"];
// nested.push('c') // this works
// console.log(nest)
collection[5439]["tracks"].push('c');
3
Should be 'track' not 'tracks'. property tracks is undefined - lissettdm

3 Answers

0
votes
collection[5439]["tracks"].push('c');

changed to: (track not tracks)

collection[5439]["track"].push('c');
0
votes

You can use concat method for this. Just like:

collection[5439]["track"].concat('c');
0
votes

collection[5439]["tracks"].push('c'); error is this line because collection[5439]["tracks"] is undefined and not an array.

Try some thing like this, initialise if not exist using ?? (nullish coalescing operator)

var collection = {
    5439: {
      albumTitle: 'ABBA Gold'
    }
  };

(collection[5439]["tracks"] ??= []).push("hello");

console.log(collection[5439]["tracks"])