|
| 1 | +// You are given a JSON object representing a part of your musical album collection. Each album has several properties and a unique |
| 2 | +// id number as its key. Not all albums have complete information. Write a function which takes an album's id (like 2548), a property prop |
| 3 | +// (like "artist" or "tracks"), and a value (like "Addicted to Love") to modify the data in this collection. If prop isn't "tracks" and |
| 4 | +// value isn't empty (""), update or set the value for that record album's property. Your function must always return the entire collection |
| 5 | +// object. There are several rules for handling incomplete data: |
| 6 | + |
| 7 | +// 1. If prop is "tracks" but the album doesn't have a "tracks" property, create an empty array before adding the new value to the |
| 8 | +// album's corresponding property. |
| 9 | + |
| 10 | +// 2. If prop is "tracks" and value isn't empty (""), push the value onto the end of the album's existing tracks array. |
| 11 | + |
| 12 | +// 3. If value is empty (""), delete the given prop property from the album. |
| 13 | + |
| 14 | +var collection = { |
| 15 | + 2548: { |
| 16 | + album: "Slippery When Wet", |
| 17 | + artist: "Bon Jovi", |
| 18 | + tracks: [ |
| 19 | + "Let It Rock", |
| 20 | + "You Give Love a Bad Name" |
| 21 | + ] |
| 22 | + }, |
| 23 | + 2468: { |
| 24 | + album: "1999", |
| 25 | + artist: "Prince", |
| 26 | + tracks: [ |
| 27 | + "1999", |
| 28 | + "Little Red Corvette" |
| 29 | + ] |
| 30 | + }, |
| 31 | + 1245: { |
| 32 | + artist: "Robert Palmer", |
| 33 | + tracks: [ ] |
| 34 | + }, |
| 35 | + 5439: { |
| 36 | + album: "ABBA Gold" |
| 37 | + } |
| 38 | +}; |
| 39 | + |
| 40 | +function updateRecords(id, prop, value) { |
| 41 | + if(value === "") delete collection[id][prop]; |
| 42 | + else if(prop === "tracks") { |
| 43 | + collection[id][prop] = collection[id][prop] || []; |
| 44 | + collection[id][prop].push(value); |
| 45 | + } else { |
| 46 | + collection[id][prop] = value; |
| 47 | + } |
| 48 | + return collection; |
| 49 | +} |
| 50 | + |
| 51 | +updateRecords(5439, "artist", "ABBA"); |
0 commit comments