Underscore JS,找到包含数组值的对象

时间:2016-06-20 23:40:00

标签: javascript jquery underscore.js

我正在寻找一个解决方案,找到包含b值的json对象。示例:查找包含" jinx"的对象在b。

示例数据。     [{     ID:1     一个:"因缘&#34 ;,     B:["不祥""凯特琳"" TRISTANA"]     },     {....},     {....}]

我理解下划线更适合键/值对,但这会有很大帮助。

感谢。

4 个答案:

答案 0 :(得分:2)

这将为您提供一个数组out的对象,其中包含数组inb包含元素jinx的所有项:

var in = [...];

var out = _.filter(in, function(item) {
   return _.contains(item.b, 'jinx');
});

答案 1 :(得分:2)

Underscore.js有一个.contains()方法,在这种情况下很有用。如果您只关注搜索对象的b密钥,那么以下内容就可以了:

var sampleData = { id:1, a:"karma", b:["jinx","caitlyn","tristana"] };

if (_.contains(sampleData.b, 'jinx') {
  // Found
} else {
  // Not found
}

根据您的评论,这是一个修订版。这使用Underscore的.filter方法将数组过滤为jink - 键控数组中包含b的数组。

var sampleData = [
  { id:1, a:"karma", b:["jinx","caitlyn","tristana"] },
  { id:2, a:"karma", b:["kinx","caitlyn","tristana"] },
  { id:3, a:"karma", b:["linx","caitlyn","tristana"] },
  { id:4, a:"karma", b:["minx","caitlyn","tristana"] },
  { id:5, a:"karma", b:["ninx","caitlyn","tristana"] },
  { id:6, a:"karma", b:["jinx","caitlyn","tristana"] },
  { id:7, a:"karma", b:["pinx","caitlyn","tristana"] },
  { id:8, a:"karma", b:["qinx","caitlyn","tristana"] },
  { id:9, a:"karma", b:["rinx","caitlyn","tristana"] }
];

var findJinx = function(data) {
  return _.first(_.filter(data, function(item) {
    if (_.contains(item.b, 'jinx')) {
      return item;
    }
  }));
}

console.log(findJinx(sampleData));

答案 2 :(得分:2)

如果您想使用underscore,可以使用_.each循环访问对象列表,然后使用_.indexOf检查每个对象中的每个b array,如此: http://jsfiddle.net/rkamelot6262/BwHxv/378/

答案 3 :(得分:1)

以下是我在纯js中的答案:

if(sample_data['b'].indexOf("jinx") != -1){
    console.log("Object in b contains jinx");
}

如果您需要支持旧浏览器,可以使用此polyfill

Array.prototype.indexOf || (Array.prototype.indexOf = function(d, e) {
    var a;
    if (null == this) throw new TypeError('"this" is null or not defined');
    var c = Object(this),
        b = c.length >>> 0;
    if (0 === b) return -1;
    a = +e || 0;
    Infinity === Math.abs(a) && (a = 0);
    if (a >= b) return -1;
    for (a = Math.max(0 <= a ? a : b - Math.abs(a), 0); a < b;) {
        if (a in c && c[a] === d) return a;
        a++
    }
    return -1
});

编辑:

因为你说你的数据看起来像这样

data=[{ id:1 ,a:"karma", b:["jinx","caitlyn","tristana"] }, {1:2}, {1:2}]
//between 1 and a you forgot ,

然后你使用的是

if(data[0]['b'].indexOf("jinx") != -1){
    console.log("Object in b contains jinx");
}