我有一个多级对象,其中定义了不同的对象。其中一些属性“叶子”是默认的并包含默认值。
我需要在 JavaScript 中构造另一个对象,该对象具有与叶子相同的“路径”,但使用默认值作为属性值。
可以将所有对象放在同一“楼层”上,并在对象上使用简单的 for 和 hasOwnProperty。但在这里,在我看来,我需要花更多时间来探索该对象,并且我不知道如何解决该对象,因为我无法使用像 object[iter1.iter2.iter3...] 这样的东西。 我需要提及的是,我正在 Eureka 版本中开发 Service Now 服务器,因此它仅支持 ECMAScript 3。
有一个例子:
我需要处理的对象(json 编码):
"schema": {"properties": { "videoCapability": { "default": "1", "type": [ "string" ], "choices": [ { "value": "0", "title": "Disabled" }, { "value": "1", "title": "Enabled" } ], }, "ice": { "properties": { "iceCapability": { "default": "1", "type": [ "string" ], "choices": [ { "value": "0", "title": "Disabled" }, { "value": "1", "title": "Enabled" } ], "name": "iceCapability"," }, "defaultcandidatetype": { "default": "0", "type": [ "string" ], "choices": [ { "value": "0", "title": "Host" }, { "value": "1", "title": "Server Reflexive" }, { "value": "2", "title": "Relayed" } ], }, etc.
我需要构建的对象:
"config": { config.properties.videoCapability = "1" config.properties.ice.properties.iceCapability = "1" config.properties.ice.properties.defaultcandidatetype = "0" }
等等
如果您想知道为什么我需要这样做,那是因为第一个对象是从远程服务器以 json 形式检索的。将此 json 编码为对象后,我需要使用正确的值修改一些属性,但不是全部。我需要将对象(已解码)发送回远程服务器。
最佳答案
lodash.get
在这里很有用:
给定这个对象:
{ a: { b: { c: { d: { e: { f: { g: {h : 1}}}}}}}}
_.get(obj, 'a.b.c.d.e.f.g.h')
返回 1
如果其中一个对象未定义,该操作将返回 undefined
而不是抛出异常。
关于javascript - 探索并获取多级对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44053714/