如果不知道键名,如何从另一个对象中获取一个对象

时间:2018-08-06 19:10:09

标签: javascript firebase react-native

在firebase中,我想提取数据,但是它返回另一个对象Object { "-LJFXZDI-O-qR572deOs": Object { "city": "almaty", "dob": "1995-08-06", "gender": "male", "height": "190", "userId": "LS1pYNjiIjRpSNV1xfXqngKAKjz2", "username": "aaaa", "weight": "80", }, }内的对象

我想获取内部对象"city": "almaty", "dob": "1995-08-06", "gender": "male", "height": "190", "userId": "LS1pYNjiIjRpSNV1xfXqngKAKjz2", "username": "aaaa", "weight": "80",

但是我确实知道此密钥“ -LJFXZDI-O-qR572deOs”,我该怎么办?

2 个答案:

答案 0 :(得分:1)

以下是使用Object.keys在不知道密钥的情况下访问密钥的方法:

var obj = {
  "-LJFXZDI-O-qR572deOs": {
    "city": "almaty",
    "dob": "1995-08-06",
    "gender": "male",
    "height": "190",
    "userId": "LS1pYNjiIjRpSNV1xfXqngKAKjz2",
    "username": "aaaa",
    "weight": "80",
  },
}

keys = Object.keys(obj); // all keys of the outer object
myKey = keys[0]; // the unknown key of the inner object
innerObject = obj[myKey];
city = innerObject.city;

console.log(city);

答案 1 :(得分:1)

您可以这样做:

const obj = {
  "-LJFXZDI-O-qR572deOs": {
    "city": "almaty",
    "dob": "1995-08-06",
    "gender": "male",
    "height": "190",
    "userId": "LS1pYNjiIjRpSNV1xfXqngKAKjz2",
    "username": "aaaa",
    "weight": "80",
  }
};
const key = Object.keys(obj)[0];
const city = obj[key].city;

console.log(key);
console.log(city);