Cant access object value from within an array

时间:2017-12-18 05:03:19

标签: javascript arrays json

{"-L0bFExUeZXB3-MUXCda":{"Comment":"GOOD","Date":"18 December","User":"OlaNord"}}

{"-L0bFCJh5SPUOWMjTRKu":{"Comment":"ok","Date":"18 December","User":"OlaNord"}}

{"-L0bFA2uzsGDizxxzN1p":{"Comment":"wewwe","Date":"18 December","User":"OlaNord"}}

I have an array of some objects inside. I need to access different values.When I try to retrieve the key name, I get undefined.

Here's my code:

// Path for selected category
var categoryRef = firebase.database().ref("forum/" + currentCategory);

categoryRef.once("value", function(snapshot) {
    firebase.auth().onAuthStateChanged(user => {
        var key = user.uid;
        var postComments = [];

        for (var key in snapshot.val()) {
            var comments = snapshot.val()[key]['comments'];
            postComments.push(comments);
        }
    })
})

enter image description here

3 个答案:

答案 0 :(得分:1)

You can try accessing the Comment as below, if the array you have posted in question can be iterated as below:

var data = [{
        "-L0bFExUeZXB3-MUXCda": {
            "Comment": "GOOD",
            "Date": "18 December",
            "User": "OlaNord"
        }
    },

    {
        "-L0bFCJh5SPUOWMjTRKu": {
            "Comment": "ok",
            "Date": "18 December",
            "User": "OlaNord"
        }
    },

    {
        "-L0bFA2uzsGDizxxzN1p": {
            "Comment": "wewwe",
            "Date": "18 December",
            "User": "OlaNord"
        }
    }
]

var postComments = [];
for (var key of data) {
    for (var values in key) {
        console.log(key[values].Comment) //access the comment
        postComments.push(key[values].Comment);
    }
}

console.log(postComments);

答案 1 :(得分:0)

// Path for selected category
var categoryRef = firebase.database().ref("forum/" + currentCategory);

categoryRef.once("value", function(snapshot) {
    firebase.auth().onAuthStateChanged(user => {
        var key = user.uid;
        var postComments = [];

        for (var key in snapshot.val()) {
            var comments = snapshot.val()[key]['Comment'];
             //CHange key Name
            postComments.push(comments);
        }
    })
})

答案 2 :(得分:0)

You can use Object.values to access the values inside a key.

var data = [{"-L0bFExUeZXB3-MUXCda":{"Comment":"GOOD","Date":"18 December","User":"OlaNord"}},{"-L0bFCJh5SPUOWMjTRKu":{"Comment":"ok","Date":"18 December","User":"OlaNord"}},{"-L0bFA2uzsGDizxxzN1p":{"Comment":"wewwe","Date":"18 December","User":"OlaNord"}}];
var result = data.reduce((r,o) => r.concat(Object.values(o).map(({Comment}) => Comment)),[]);
console.log(result);