2017-09-01 58 views
0

我正在为矿山对象进行搜索筛选。但他只显示像确切的结果:Typeof仅显示确切结果

阵列数据:

name => 'foo', 
name => 'fa', 
name => 'bar', 

我所是:

getObjects(array, 'name', 'foo'); 

如果我搜索的 'F' 我什么也没得到。当我搜索'foo'时,我得到'foo'。我想要的是,如果我在'f'上搜索,我想'foo'和'fa'。

代码

function getObjects(obj, key, val) { 
    var objects = []; 
    for (var i in obj) { 
     if (!obj.hasOwnProperty(i)) continue; 
     if (typeof obj[i] === 'object') { 
      objects = objects.concat(getObjects(obj[i], key, val)); 
     } else if (i == key && obj[key] == val) { 
      objects.push(obj); 
     } 
    } 
    return objects; 
} 

我想听听您的意见,非常感谢!

+1

请加个例子。你的意思是要比较的关键还是价值? –

+0

不知道你想达到什么,但通过使用“===”,它只会匹配typeof ..甚至2 ===“2”将在条件检查中失败。 –

+0

我编辑了这个问题。 –

回答

1
var a = 'blabla'; 
alert(a.includes('la')) 

function getObjects(obj, key, val) { 
    var objects = []; 
    for (var i in obj) { 
     if (!obj.hasOwnProperty(i)) continue; 
     if (typeof obj[i] === 'object') { 
      objects = objects.concat(getObjects(obj[i], key, val)); 
     } else if (i.includes(key) && obj[key].includes(val)) { 
      objects.push(obj); 
     } 
    } 
    return objects; 
} 
1

你可以使用String#indexOf,或用ES6 String#includes

function getObjects(obj, key, val) { 
 
    var objects = []; 
 
    for (var i in obj) { 
 
     if (!obj.hasOwnProperty(i)) continue; 
 
     if (typeof obj[i] === 'object') { 
 
      objects = objects.concat(getObjects(obj[i], key, val)); 
 
     } else if (i.indexOf(key) !== -1 && obj[key].indexOf(val) !== -1) { 
 
      objects.push(obj); 
 
     } 
 
    } 
 
    return objects; 
 
} 
 

 
var array = [{ name: 'foo' }, { name: 'fa' }, { name: 'bar' }]; 
 
    
 
console.log(getObjects(array, 'name', 'f'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

是不是'String#indexOf' /'String#includes'? (OP的实际数据有点模糊) – Cerbrus

+0

第二个给出了一切,但不是正确的。剩下的只有当我搜索'foo'时才给我'foo',当我搜索'f'时,我没有得到'foo'或其他所有'f'。 –

0

i == key && obj[key] == val 

可以使用

i.includes(key) && obj[key].includes(val) 
1

让这个lot更简单。

如果我读的问题,正确的,这是你的数据:

var array = [{name: 'foo'},{name: 'fa'},{name: 'bar'}]; 

然后,它没有那么多的工作让所有的项目特定密钥包含特定值:

var array = [{name: 'foo'},{name: 'fa'},{name: 'bar'}]; 
 

 
function getObjects(array, key, value) { 
 
    return array.filter(function(item) { // I only want items that... 
 
     return item[key] &&    // Have the current key 
 
      item[key].includes(value); // And it contains the value I'm looking for. 
 
    }); 
 
} 
 

 
console.log(getObjects(array, 'name', 'foo')); 
 
console.log(getObjects(array, 'name', 'a')); 
 
console.log(getObjects(array, 'name', 'f')); 
 
console.log(getObjects(array, 'baz', 'woo')); // No results for bad key.

请注意,您可以使用item.hasOwnproperty(key) &&而不是item[key] &&,如果这是索姆你需要担心的事情。

+0

非常感谢!但是,返回并不是关键,而是关键的孔洞对象。 –

+0

@PieterDijkstra:我不确定你的意思。我的例子中的返回值不是你想要的? – Cerbrus

+0

返回值是一个数组不是项[键],但只有项目:D但其余的代码是确定的。 –