从对象获取元素并与Array - Jquery进行比较

时间:2017-01-23 20:10:56

标签: javascript jquery arrays json loops

var words = [
    {word: 'cow', explain: 'animal'},
    {word: 'apple', explain: 'fruit'},
    {word: 'dog', explain: 'animal'}];
var word2 = ["cow", "dog"];

如何将单词 word2 进行比较,并使用Jquery为匹配的单词 red 着色?

我的问题在于对象,我无法提取 word

中的元素 你能帮帮我吗? 谢谢

4 个答案:

答案 0 :(得分:0)

对于问题的第一部分,您可以使用Array.filter()

var words = [
    {word: 'cow', explain: 'animal'},
    {word: 'apple', explain: 'fruit'},
    {word: 'dog', explain: 'animal'}
];
var word2 = ["cow", "dog"];

var wordsInWord2 = words.filter(function (obj) {
    return word2.indexOf(obj.word) !== -1;
});

假设您的Javascript在网络浏览器中运行,问题的第二部分将需要HTML,因为Javascript并没有直接输出彩色文字的方法。

答案 1 :(得分:0)

尝试类似

的内容
words.filter( function(e,i,arr){
  return word2.filter(e2 => e.word === e2).length; // only keep the words form word2
}).forEach( function(e,i,arr){
  /*do something where e is of the form {word: ..., explain: ...} */
});

答案 2 :(得分:0)

var words = [
    {word: 'cow', explain: 'animal'},
    {word: 'apple', explain: 'fruit'},
    {word: 'dog', explain: 'animal'}];
var word2 = ["cow", "dog"];

var result = [];
words.forEach(function(e){
    if(word2.indexOf(e.word) != -1)
        result.push(e);
});

console.log(result);

答案 3 :(得分:-1)

这很简单......但你需要先将单词转换为对象

var words = {
  "cow": { "explain": "animal" },
  "apple": { "explain": "fruit" },
  "dog": { "explain": "animal" }
};

然后

for (var i = 0; i < words2.length; i++)
{
    if (words[words2[i]])
    {
        // found a math at index i
    }
}