This code updates the object properties and their values but when I try to return the object, I get [object Object] on my screen. How do I Return the whole object?
JavaScript
x
2
1
<div id="demo"></div>
2
JavaScript
1
40
40
1
//the javascript code
2
const recordCollection = {
3
2548: {
4
albumTitle: 'Slippery When Wet',
5
artist: 'Bon Jovi',
6
tracks: ['Let It Rock', 'You ive Love a Bad Name']
7
},
8
2468: {
9
albumTitle: '1999',
10
artist: 'Prince',
11
tracks: ['1999', 'Little Red Corvette']
12
},
13
1245: {
14
artist: 'Robert Palmer',
15
tracks:[]
16
},
17
5439: {
18
albumTitle: 'ABBA Gold'
19
}
20
}
21
22
function updateRecords(records, id, prop, value) {
23
let demo = document.getElementById('demo');
24
25
if (prop !== "tracks" && value !== "") {
26
records[id][prop] = value;
27
} else if (prop === "tracks" && records[id].hasOwnProperty("tracks") === false) {
28
// let add = [];
29
records[id][prop] == [value];
30
} else if (prop === "tracks" && value !== "") {
31
records[id][prop].push(value);
32
} else if (value === "") {
33
delete records[id][prop];
34
}
35
36
demo.innerHTML = records;
37
return demo;
38
}
39
40
updateRecords(recordCollection, 5439, 'artist', 'ABBA');
JavaScript
1
2
1
<!-- The html code -->
2
<div id="demo"></div>
Advertisement
Answer
You have to create a string at some point. JSON.stringify(records)
is the closest you will get to printing the object.
JavaScript
1
40
40
1
//the javascript code
2
const recordCollection = {
3
2548: {
4
albumTitle: 'Slippery When Wet',
5
artist: 'Bon Jovi',
6
tracks: ['Let It Rock', 'You ive Love a Bad Name']
7
},
8
2468: {
9
albumTitle: '1999',
10
artist: 'Prince',
11
tracks: ['1999', 'Little Red Corvette']
12
},
13
1245: {
14
artist: 'Robert Palmer',
15
tracks:[]
16
},
17
5439: {
18
albumTitle: 'ABBA Gold'
19
}
20
}
21
22
function updateRecords(records, id, prop, value) {
23
let demo = document.getElementById('demo');
24
25
if (prop !== "tracks" && value !== "") {
26
records[id][prop] = value;
27
} else if (prop === "tracks" && records[id].hasOwnProperty("tracks") === false) {
28
// let add = [];
29
records[id][prop] == [value];
30
} else if (prop === "tracks" && value !== "") {
31
records[id][prop].push(value);
32
} else if (value === "") {
33
delete records[id][prop];
34
}
35
36
demo.innerHTML = JSON.stringify(records, null, 2);
37
return demo;
38
}
39
40
updateRecords(recordCollection, 5439, 'artist', 'ABBA');
JavaScript
1
2
1
<!-- The html code -->
2
<pre id="demo"></pre>