【发布时间】:2016-11-18 12:45:35
【问题描述】:
我有一个对象。我想检查其中是否存在特定属性。
问题是:我正在寻找的属性,可以在任何地方,即:对象的结构是不安全的。
例如:
obj1 = { "propIWant": "xyz" }
obj2 = { "prop1": [ {"key": "value"}, {"key":"value"}, 1, {"key": { "propIWant": "xyz"}}]
我尝试了以下方法,但似乎失败了:
var lastTry = function(entry){
// if entry is an array
if(typeof entry === 'object' && entry instanceof Array){
for(var i in entry)
entry[i] = this.lastTry(entry[i]);
}
// if entry is a normal object
else if(typeof entry === 'object'){
// iterate through the properties of the entry
for(var key in entry){
console.log('key is: ', entry[key])
// in case the entry itself is an array
if(typeof entry[key] === 'object' && entry[key] instanceof Array){
for(var i in entry[key]){
entry[key][i] = this.lastTry(entry[key][i]);
}
}
// in case the entry is a simple object
else if(typeof entry[key] === 'object') {
console.log('entry[key] is an object', entry[key], key)
// if we directely find the property.. modify it
if(entry[key].hasOwnProperty('_internal_url')){
**entry[key]['_internal_url'] = "http://localhost:4000"+entry[key]['_internal_url'];** <-- My objective
}
else{
// call this method again on that part
// for(var i in entry[key]){
// if(typeof entry[key][i] === 'object')
// entry[key][i] = this.lastTry(entry[key][i]);
// }
}
}else{
console.log('not found')
}
}
}
}
有人可以帮我解决吗?我找到了以下内容:Find by key deep in a nested object 但是,我不想返回找到的部分,而是想编辑属性并返回具有修改后属性的整个对象,而不仅仅是具有该属性的对象。
【问题讨论】:
-
@DominicTobias 正在调查
标签: javascript node.js object recursion