如何在JavaScript中从高度嵌套的json对象中优雅地获得特定值?



这是我的json对象名称data

{
"data": {
"id": "---------",
"type": "licenses",
"attributes": {
"name": "Floating Point Lic",
"key": "-----------",
"expiry": "2022-07-30T19:11:30.738Z",
"status": "ACTIVE",
"uses": 0,
"suspended": false,
"scheme": "ED25519_SIGN",
"encrypted": false,
"strict": true,
"floating": true,
"protected": true,
"maxMachines": 10,
"maxProcesses": null,
"maxCores": null,
"maxUses": null,
"requireHeartbeat": false,
"requireCheckIn": false,
"lastValidated": "2022-07-07T08:33:58.195Z",
"lastCheckIn": null,
"nextCheckIn": null,
"metadata": {         
"role": "sde"
},
"created": "2022-06-30T19:11:30.736Z",
"updated": "2022-07-07T08:33:58.199Z"
},
"relationships": {
"account": {
"links": {
"related": "------------"
},
"data": {
"type": "accounts",
"id": "------------"
}
},
"product": {
"links": {
"related": "------------------"
},
"data": {
"type": "products",
"id": "This I need"
}
},
"policy": {
"links": {
"related": "---------"
},
"data": {
"type": "policies",
"id": "---------------"
}
},
"group": {
"links": {
"related": "------------"
},
"data": null
},
"user": {
"links": {
"related": "---------------"
},
"data": null
},
"machines": {
"links": {
"related": "-------------------"
},
"meta": {
"cores": 0,
"count": 0
}
},
"tokens": {
"links": {
"related": "----------------"
}
},
"entitlements": {
"links": {
"related": "------------------"
}
}
},
"links": {
"self": "-------------"
}
},
"meta": {
"ts": "2022-07-07T08:33:58.204Z",
"valid": false,
"detail": "must have at least 1 associated machine",
"constant": "NO_MACHINES"
}

}

数据,那么他们的关系然后是产品数据id我希望

我现在通过写作得到它r("数据")("数据")("关系")("产品")("数据")("id")

r就是这个对象,但它看起来一点也不优雅。他们有什么更好的方法来获取这个吗?

用点代替括号:

const wantedId = r.data.relationships.product.data.id;

括号只有在使用动态引用属性时才有用。

最新更新