Reputation: 31
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.
var collection = {
1245: {
artist: "Robert Palmer",
tracks: [ ]
},
5439: {
album: "ABBA Gold"
}
};
var collectionCopy = JSON.parse(JSON.stringify(collection));
function update(id, prop, value) {
if (value !== '' && prop == 'tracks') {
collectionCopy[id][prop].push(value);
return collectionCopy;
}
update(1245, "tracks", "Addicted to Love");
It says collectionCopy[id][prop].push(value) is not a function, i don't know why,but collectionCopy[id][prop] is actually an array. Thanks for help!
Upvotes: 2
Views: 40
Reputation: 36630
Your if statement is not correctly closed. Try to structure your code more neatly using an IDE which can usually do this for you. The code should be the following:
var collection = {
1245: {
artist: "Robert Palmer",
tracks: []
},
5439: {
album: "ABBA Gold"
}
};
var collectionCopy = JSON.parse(JSON.stringify(collection));
function update(id, prop, value) {
if (value !== '' && prop == 'tracks') {
collectionCopy[id][prop].push(value);
return collectionCopy;
}
}
update(1245, "tracks", "Addicted to Love");
console.log(collection);
Upvotes: 0
Reputation: 4099
You're missing a } in your if statement in update(). Fixed up code below works just fine:
var collection = {
1245: {
artist: "Robert Palmer",
tracks: [ ]
},
5439: {
album: "ABBA Gold"
}
};
var collectionCopy = JSON.parse(JSON.stringify(collection));
function update(id, prop, value) {
if (value !== '' && prop == 'tracks') {
collectionCopy[id][prop].push(value);
}
return collectionCopy;
}
update(1245, "tracks", "Addicted to Love");
Output:
{ 1245: { artist: 'Robert Palmer', tracks: [ 'Addicted to Love' ] },
5439: { album: 'ABBA Gold' } }
Upvotes: 1