0

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?

3 Answers 3

1

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);
}

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.