我想找到最有效的方法来搜索对象,其中每个值都是数组的数组。搜索函数将接收一个数组[0,1,0]
,查找包含该数组的所有项,并返回一个匹配键的数组。
var items = {
"bob":[[0,0,0],[0,0,1],[0,1,0]],
"joe":[[0,0,0],[1,1,1],[0,1,0]],
"ike":[[0,0,0],[0,0,2],[1,1,1]]
}
例如
[0,0,0]
将返回["bob","joe","ike"]
[0,1,0]
将返回["bob","joe"]
[1,1,1]
将返回["joe","ike"]
[0,0,2]
返回["ike"]
使用Object#keys
和Array#reduce
,遍历对象的键。在每个属性中,从它的值创建一个hash
,然后使用Object#hasOwnProperty
,检查目标子数组是否在其中,这将决定是否在结果列表中包含当前键:
const getMatchingProps = (obj = {}, subArr = []) =>
Object.keys(obj).reduce((matchingKeys, key) => {
const hash = obj[key].reduce((acc, arr, i) => ({ ...acc, [arr]: i }), {});
return hash.hasOwnProperty(subArr) ? [...matchingKeys, key] : matchingKeys
}, []);
const items = {
"bob": [[0,0,0],[0,0,1],[0,1,0]],
"joe": [[0,0,0],[1,1,1],[0,1,0]],
"ike": [[0,0,0],[0,0,2],[1,1,1]]
};
console.log( getMatchingProps(items, [0,0,0]).join() );
console.log( getMatchingProps(items, [0,1,0]).join() );
console.log( getMatchingProps(items, [1,1,1]).join() );
console.log( getMatchingProps(items, [0,0,2]).join() );
这将得到您想要的结果,但它可能不是最有效的速度。
const items = {
bob: [
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
],
joe: [
[0, 0, 0],
[1, 1, 1],
[0, 1, 0],
],
ike: [
[0, 0, 0],
[0, 0, 2],
[1, 1, 1],
],
};
const test = (items, target) => {
return Object.entries(items)
.filter((item) => {
return item[1].some((list) => {
return (
list.length === target.length &&
list.every((number, index) => {
return number === target[index];
})
);
});
})
.map((item) => {
return item[0];
});
};
console.log(test(items, [0, 0, 0])); // [ 'bob', 'joe', 'ike' ]
console.log(test(items, [0, 1, 0])); // [ 'bob', 'joe' ]
console.log(test(items, [1, 1, 1])); // [ 'joe', 'ike' ]
console.log(test(items, [0, 0, 2])); // [ 'ike' ]
:使用Object.entries()
获取items
的键和值。然后使用some
函数过滤出该列表,其中值列表中必须有一些数组,其中数组等于目标数组。在本例中,为了查看数组是否相等,我使用every
检查了长度是否相等以及所有数字是否相等。在条目列表被过滤之后,我们使用map
将名称取出。