2016-12-06 146 views
-7

我在一个角度范围内有一个基本上包含每个迭代中的对象的数组。我之前使用了indexOf()函数来检查数组中是否存在值 - 但是如何检查对象字值中是否存在值?在javascript中搜索对象中的值

我想使用一个foreach循环,只是检查一个单词是否存在于规则数组中,如下所示 - 如何实现这个最好的方法?

rules = []; 

rules[0] = { word:"house"} 
rules[1] = { word:"shoes"} 
rules[2] = { word:"tools"} 
+1

'Object.values(O)。有些(V => v ===针)'? – Ben

+4

[请在发帖前搜索](/ search?q =%5Bjs%5D + search + array + of + objects),关于该主题有几十个问题(有数百个答案),您的问题至少回答一个其中可能有几个。更多关于搜索[这里](/帮助/搜索)。 –

+3

可能的重复[如何检查数组是否包含JavaScript中的对象?](http://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an- object-in-javascript) –

回答

1

rules = [] 
 

 
rules[0] = { word:"house"} 
 
rules[1] = { word:"shoes"} 
 
rules[2] = { word:"tools"} 
 
rules[3] = { sentence:"horse"} 
 

 
rules.forEach(rule => { 
 
    if (rule.word) { 
 
     console.log('Exist. Value:', rule.word) 
 
    } else { 
 
     console.log('Doesn\'t Exist.') 
 
    } 
 
})

希望这有助于!

1
for(var i =0;i < rules.length;i++){ 
    if(rules[i].word === 'valueYouWantToCheck'){ 
    // do whatever you want to do 
    } 
} 

尝试...... :)

+0

他提到了问题,他想用''for forE'''循环。 – bharadhwaj

+0

@bharadhwaj foreach将服务相同。只是他必须通过索引和item.forEach(someFunction)和像someFunction(index,item)这样写函数{} –

+0

这是一个工作解决方案,我同意!但他明确提到他**需要使用'''forEach''循环。这就是我通知你的原因!而且他只是想知道这样一个关键字是否存在,而不是将它与某个值进行比较,我希望!否则,这是一个很好的解决方案! – bharadhwaj

-1
rules = []; 

rules[0] = { word:"house"} 
rules[1] = { word:"shoes"} 
rules[2] = { word:"tools"} 

for(var i=0; i<rules.length ; i++) 
{ 
    rules[i]["word"]=='valueforComparison'; // or rules[i].word=='valueforComparison'; 
} 
1

您可以使用此

var rules = []; 
rules[0] = { word:"house"} 
rules[1] = { word:"shoes"} 
rules[2] = { word:"tools"} 
rules.forEach(function(item){ 
    console.log(item.word) // your word of choice 
}) 

您还可以使用filter功能。如果你需要的单词匹配,将返回对象,否则它会返回一个空数组

var getValue = rules.filter(function(item){ 
    return item.word=='house'; 
}) 
console.log(getValue) 

除此之外,您还可以使用.find方法

rules.find(function(item){ 
    return item.word=="house"; 
})