根据条件动态选择属性(或嵌套对象)。它可以是以下4种可能性中的一种:
var tempData = o.title ? o["properties"] || o["items"]["properties"] : o[k]["properties"] || o[k]["items"]["properties"];
然后我得到这个新数据,我想替换上面选中的。
var newData = //some new Object
我想用新数据替换上面选择的内容。我可以执行以下操作(再次检查条件并设置新数据):
if(o.title){
if (o["properties"]) {
o["properties"] = newData;
} else if (o["items"]["properties"]) {
o["items"]["properties"] = newData;
}
}else{
if (o[k]["properties"]) {
o[k]["properties"] = newData;
} else if (o[k]["items"]["properties"]) {
o[k]["items"]["properties"] = newData;
}
}
但它看起来并不好。实现这一目标的更复杂方法是什么?
答案 0 :(得分:1)
好的,从我在这里可以理解的,它就像你正试图取代"属性"使用新数据,您希望能够动态完成,或者我可以说,无论结构如何,您都需要这样做。
让我们看看,如果你的目标是最终的"属性",那么就这样做:
function recReplace(current,target,replacement){
for (var i in current){
if (i == target){
current[i] = replacement;
}
else{
recReplace(current[i],target,replacement);
}
}
}
最后你打电话给
recReplace(o,"properties",newData);
但这将取代整个"属性"使用DFS方式的newData键,如果只想在第一次出现时替换它,可以执行附加条件
答案 1 :(得分:1)
目前还不清楚您是否通常尝试使用properties
替换任何newData
属性,或者您是否希望它特别是您在代码中指定的属性之一。我假设您只想替换您在代码中明确显示的内容。
注意:以下假设properties
属性的值无法计算为false
。如果它的值可能为false
,则会失败。
作为第一关,我会做类似的事情:
var p;
if (o.title) {
p=o;
} else {
p=o[k];
}
if (p.properties) {
p.properties = newData;
} else if (p.items.properties) {
p.items.properties = newData;
}
然而,这取决于:
o
不是null
或undefined
。o.title
,则false
不会评估为o.title
。k
有效/已定义。p
(即o[k]
)不是null
或未定义(即是对象)p.properties
不评估为false
p.items
不是null
或未定义(即是对象)p.items.properties
不评估为false
更强大的实施方案是:
if (typeof o === 'object' && o !== null) {
var p;
if (o.hasOwnProperty('title')) {
p = o;
} else {
p = o[k];
}
if (typeof p === 'object' && p !== null) {
if (p.hasOwnProperty('properties')) {
p.properties = newData;
} else if (typeof p.items === 'object' && p.items !== null
&& p.items.hasOwnProperty('properties')) {
p.items.properties = newData;
}
}
}
这仍然依赖于:
k
有效/已定义。基本上,如果您知道
,可以使用if(o.title)
等快捷方式来测试是否存在
o
的可能值不包括可能导致您的代码出错的内容(例如o
为null
或undefined
),o.title
的可能值在属性实际存在时不会评估为false(例如o.title
是null
,undefined
(是的,该属性可以存在,但是具有值undefined
),false
,0
,''
等。)。如果您要在代码的其他区域执行替换,或者如果您要使用硬编码items
和properties
以外的属性键,那么您应该创建一个函数。假设您只是 在代码的这一部分中执行此替换,使用变量来保存您要查找的对象properties
比创建函数更快/更有效。< / p>