Skip to content
Advertisement

how do I return the whole object without seeing [object Object]?

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?

<div id="demo"></div>

//the javascript code
const recordCollection = {
        2548: {
            albumTitle: 'Slippery When Wet',
            artist: 'Bon Jovi',
            tracks: ['Let It Rock', 'You ive Love a Bad Name']
        },
        2468: {
            albumTitle: '1999',
            artist: 'Prince',
            tracks: ['1999', 'Little Red Corvette']
        },
        1245: {
            artist: 'Robert Palmer',
            tracks:[]
        },
        5439: {
            albumTitle: 'ABBA Gold'
        }
    }

    function updateRecords(records, id, prop, value) {
        let demo = document.getElementById('demo');
        
        if (prop !== "tracks" && value !== "") {
            records[id][prop] = value;
        } else if (prop === "tracks" && records[id].hasOwnProperty("tracks") === false) {
            // let add = [];
            records[id][prop] == [value];
        } else if (prop === "tracks" && value !== "") {
            records[id][prop].push(value);
        } else if (value === "") {
            delete records[id][prop];
        }

        demo.innerHTML = records;
        return demo;
    }

    updateRecords(recordCollection, 5439, 'artist', 'ABBA');
<!-- The html code -->
<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.

//the javascript code
const recordCollection = {
        2548: {
            albumTitle: 'Slippery When Wet',
            artist: 'Bon Jovi',
            tracks: ['Let It Rock', 'You ive Love a Bad Name']
        },
        2468: {
            albumTitle: '1999',
            artist: 'Prince',
            tracks: ['1999', 'Little Red Corvette']
        },
        1245: {
            artist: 'Robert Palmer',
            tracks:[]
        },
        5439: {
            albumTitle: 'ABBA Gold'
        }
    }

    function updateRecords(records, id, prop, value) {
        let demo = document.getElementById('demo');
        
        if (prop !== "tracks" && value !== "") {
            records[id][prop] = value;
        } else if (prop === "tracks" && records[id].hasOwnProperty("tracks") === false) {
            // let add = [];
            records[id][prop] == [value];
        } else if (prop === "tracks" && value !== "") {
            records[id][prop].push(value);
        } else if (value === "") {
            delete records[id][prop];
        }

        demo.innerHTML = JSON.stringify(records, null, 2);
        return demo;
    }

    updateRecords(recordCollection, 5439, 'artist', 'ABBA');
<!-- The html code -->
<pre id="demo"></pre>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement