给定数组参数ary ["value", "value2"]
我想遍历一个对象对象,找到两个数组值的匹配项。我试过这样:
function findMatch (ary) {
storageArray = [];
mykeys = [];
myvalues = [];
for (var i = 0; i < ary.length; i++) {
for (obj in object) {
for (key in object[obj]) {
if (ary[i] in object[obj]) {
mykeys.push(key);
myvalues.push(object[obj][ary[i]]);
}
}
}
storageArray .push(mykeys, myvalues);
return storageArray;
}
var object = {
"subobject" :
{
'key' : 'value',
'key2' : 'value2',
'key3' : 'value3'
},
"subobject2" :
{
'key4' : 'value4'
},
}
目标:能够为k : v
ary
对
含义...因为ary
有value
和value2
...我想要从key : value
和key2 : value2
的对象返回一个匹配项。
到目前为止,这a)不起作用,b)似乎不是最有效的方法(3代表循环...)
答案 0 :(得分:1)
这与你的方式类似,而且有效。
function findMatch(array, object) {
var result = [];
for (var sub in object) {
var subObj = object[sub];
for (var key in subObj) {
for (var i = 0; i < array.length; i++) {
if (subObj[key] === array[i]) {
result.push({
k: key,
v: subObj[key]
});
}
}
}
}
return result;
}
var result = findMatch(['value', 'value2'], object);
for (var i = 0; i < result.length; i++) {
console.log(result[i].k + " : " + result[i].v);
}
以下是使用查找对象的另一种方法:
function findMatch(array, object) {
var result = [];
var lookup = {};
for (var sub in object) {
var subObj = object[sub];
for (var key in subObj) {
var value = subObj[key];
if (!lookup[value]) {
lookup[value] = [];
}
lookup[value].push(key);
}
}
for (var i = 0; i < array.length; i++) {
var val = array[i];
var foundArr = lookup[val];
if (foundArr) {
for (var j = 0; j < foundArr.length; j++) {
result.push({
k: foundArr[j],
v: val
});
}
}
}
return result;
}
var result = findMatch(['value', 'value2'], object);
for (var i = 0; i < result.length; i++) {
console.log(result[i].k + " : " + result[i].v);
}