1 // Setup 2 var collection = { 3 "2548":{ 4 "album": "Slippery When Wet", 5 "artist": "Bon Jovi", 6 "tracks": [ 7 "Let It Rock", 8 "You Give Love a Bad Name" 9 ] 10 }, 11 "2468":{ 12 "album": "1999", 13 "artist": "Prince", 14 "tracks": [ 15 "1999", 16 "Little Red Corvette" 17 ] 18 }, 19 "1245":{ 20 "artist": "Robert Palmer", 21 "tracks": [] 22 }, 23 "5439":{ 24 "album": "ABBA Gold" 25 } 26 }; 27 28 // Keep a copy of the collcection for tests 29 var collectionCopy = JSON.parse(JSON.stringify(collection)); 30 31 // update 32 function updateRecords(id,prop,value){ 33 if(value === ""){ 34 // 如果值为空, 则删除这个属性 35 delete collection[id][prop]; 36 }else if (prop === "tracks"){ 37 collection[id][prop] = collection[id][prop] || []; 38 // 如果 track 存在, 则不做变动; 若不存在, 则创建一个track, 并将[]赋给它 39 collection[id][prop].push(value); // 赋值 (添加至末端) 40 } else{ 41 collection[id][prop] = value; 42 } 43 44 return collection; 45 } 46 47 // Alter values below to test your code 48 console.log(updateRecords(5439,"artist","ABBA"));
LINK: https://www.youtube.com/watch?v=PkZNo7MFNFg&t=241s 2:03:00