考虑以下json模型:
{
"idNumber": "8908904",
"firstname": "John",
"lastname": "Doe",
"address": "12 Kent, Pluto, CBD, 67435"
}
有没有一种方法可以仅读取此json模型中的属性?
预期输出:
[ "idNumber", "firstname", "lastname", "address" ]
答案 0 :(得分:2)
使用以下代码-
let keyArray = Object.keys({
"idNumber": "8908904",
"firstname": "John",
"lastname": "Doe",
"address": "12 Kent, Pluto, CBD, 67435"
});
let requiredResponse = {keyArray};
console.log(requiredResponse.keyArray) //[ "idNumber", "firstname", "lastname", "address" ]
答案 1 :(得分:1)
const json = {
"idNumber": "8908904",
"firstname": "John",
"lastname": "Doe",
"address": "12 Kent, Pluto, CBD, 67435"
};
json.entries = Object.keys(json);
正是您所需要的,它将返回与您期望的数组完全相同的
更新: 您不能在没有键的情况下将数组存储在Object中,因此您可能需要像上面一样在此将数组分配给新键,并且输出将如下所示:
{
"idNumber": "8908904",
"firstname": "John",
"lastname": "Doe",
"address": "12 Kent, Pluto, CBD, 67435",
"entries": ["idNumber", "firstname", "lastname", "address"]
};