我有一個對象。我想檢查一下是否存在特定的屬性。查找對象內的特定屬性
問題是:我正在查找的屬性可能在任何地方,即:對象的結構是不確定的。
例如:
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尋找到它 –
的[在嵌套的JSON對象鍵深查找]可能的複製(http://stackoverflow.com/questions/15523514/find-by-key-deep-in-nested- json-object) – morels