Reputation: 3340
It might be duplicate, sorry for that but I couldn't understand (New to firebase and JS).
I have a snapshot from firebase, but I couldn't understand how to parse that snapshot object.
Here is my code:
var obj = snapshot.val();
console.log(JSON.stringify(obj));
It outputs following:
{"-KpxDFnJEt2xlD21lzyh":{"chatid":"6qKi8xO5vxdrcKFd5wqUNUkTupg2PNQjC87cFNcKxYkDoYMdhH95LCK2"}}
I want to get this -KpxDFnJEt2xlD21lzyh
value in a separate variable and chatid
into separate variable, but not be able to.
What should I do?
Upvotes: 0
Views: 1320
Reputation: 22574
You can access keys in an object Object.Keys
, it will return an array. At index 0 you will have your first key. Similarly, to access value, you can use Object.Values
, it will return an array.
var response = {"-KpxDFnJEt2xlD21lzyh":{"chatid":"6qKi8xO5vxdrcKFd5wqUNUkTupg2PNQjC87cFNcKxYkDoYMdhH95LCK2"}};
var id = Object.keys(response);
var chats = Object.values(response);
console.log(id[0]);
console.log(chats[0]['chatid']);
Upvotes: 0
Reputation: 15461
To get the key name and its chatid
value:
var json = {
"-KpxDFnJEt2xlD21lzyh": {
"chatid": "6qKi8xO5vxdrcKFd5wqUNUkTupg2PNQjC87cFNcKxYkDoYMdhH95LCK2"
}
}
for (key in json) {
if (!json.hasOwnProperty(key)) continue;
console.log(key);
console.log(json[key].chatid);
}
Upvotes: 1
Reputation: 20546
Something like the following?
for (var i = 0; i < Object.keys(obj); i++) {
console.log(Object.keys(obj)[i]); // -KpxDFnJEt2xlD21lzyh
console.log(obj[Object.keys(obj)[i]]["chatid"]); // 6qKi8xO5vxdrcKFd5wqUNUkTupg2PNQjC87cFNcKxYkDoYMdhH95LCK2
}
That will loop through the JSON object getting each key, printing the key and chat id.
Upvotes: 0