在下面的对象中,通过它的键(itemID)检索嵌套对象的最有效方法是什么(考虑到性能,假设对象可能很大)?
显然,我可以通过首先引用每个父项(searchResults.page2.item3)来访问该对象,但是如何仅使用itemID从searchResults中检索item3,假设我不知道它是什么页面。 s on?
var searchResults = {
page1 : {
item1 : {},
item2 : {}
},
page2 : {
item3 : {},
item4 : {}
}
}
答案 0 :(得分:1)
只需循环浏览您的对象即可。这是一个有效的解决方案。希望它有所帮助!
var searchResults = {
page1 : {
item1 : {},
item2 : {}
},
page2 : {
item3 : { id: 3},
item4 : {}
}
}
for(var i in searchResults){
var pageNumber = searchResults[i];
for(var j in pageNumber){
var deeperProperty = pageNumber[j];
if(deeperProperty.hasOwnProperty("id") && deeperProperty.id === 3){
console.log(deeperProperty);
}
}
}
答案 1 :(得分:1)
使用递归函数只检查整个对象,直到找到item3
var searchResults = {
page1: {
item1: {
id: 1
},
item2: {
id: 2
}
},
page2: {
item3: {
id: 3
},
item4: {
id: 4
}
}
}
/* start the operation */
recurse_object(searchResults, 0);
function recurse_object(obj, curIdx) {
/* create array with all keys for an object */
var keys = Object.keys(obj);
/* check if we have gone through all of the object's keys */
if (curIdx < keys.length) {
/* if not, grab the key associated with curIdx */
var keyVal = keys[curIdx];
if (keyVal == 'item3') {
console.log("FOUND ITEM3 ID! " + obj.item3.id);
} else {
/* check if the current item has any sub-keys to check */
if (Object.keys(obj[keyVal]).length > 0) {
/* check the any keys that exist in a particular key */
recurse_object(obj[keyVal], 0);
}
/* now increase the index to check for the next key on object */
curIdx++;
recurse_object(obj, curIdx);
}
}
}
&#13;
var searchResults = {
page1: {
item1: {
id: 1
},
item2: {
id: 2
}
},
page2: {
item3: {
id: 3
},
item4: {
id: 4
}
},
page20: {
subPage1: {
item3: {
id: 6
}
},
item5: {
subItem2: {
deepItem1: {
item3: {
id: 10
}
}
}
}
}
}
recurse_object(searchResults, 0);
function recurse_object(obj, curIdx) {
var keys = Object.keys(obj);
if (curIdx < keys.length) {
var keyVal = keys[curIdx];
if (keyVal == 'item3') {
console.log("FOUND ITEM3 ID! " + obj.item3.id);
} else {
if (Object.keys(obj[keyVal]).length > 0) {
recurse_object(obj[keyVal], 0);
}
curIdx++;
recurse_object(obj, curIdx);
}
}
}
&#13;
答案 2 :(得分:0)
这似乎没有什么效率,但它确实是你所要求的“我能不能只使用itemID从searchResults中检索item3,假设我不知道它在哪个页面上?”去。
y = 2016
vec = seq(from = y+1, to = y + 60*4, by = 1)
#Start at y+1 so that we exclude the given year
#Choose 60 to make sure we get at least 50 leap years
library(lubridate)
head(vec[leap_year(vec)], 50)
# [1] 2020 2024 2028 2032 2036 2040 2044 2048 2052
#[10] 2056 2060 2064 2068 2072 2076 2080 2084 2088
#[19] 2092 2096 2104 2108 2112 2116 2120 2124 2128
#[28] 2132 2136 2140 2144 2148 2152 2156 2160 2164
#[37] 2168 2172 2176 2180 2184 2188 2192 2196 2204
#[46] 2208 2212 2216 2220 2224