最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

checking if javascript array contains value using underscorejs - Stack Overflow

programmeradmin3浏览0评论

I have an array of cars like this:

[{ name:"Toyota Minivan", id:"506" }, { name:"Honda Civic", id:"619" }]

I am trying to check whether the array contains a certain id.

I have tried

var x =!!_.where(cars, {id:'506'}).length;

expecting it to return true if the array contains the id, but it always returns false.

What am I doing here ?

Btw, I don't have to use underscore.js if there is a better way of doing this.

thanks Thomas

I have an array of cars like this:

[{ name:"Toyota Minivan", id:"506" }, { name:"Honda Civic", id:"619" }]

I am trying to check whether the array contains a certain id.

I have tried

var x =!!_.where(cars, {id:'506'}).length;

expecting it to return true if the array contains the id, but it always returns false.

What am I doing here ?

Btw, I don't have to use underscore.js if there is a better way of doing this.

thanks Thomas

Share Improve this question edited Nov 21, 2013 at 0:25 Gabe Moothart 32.1k14 gold badges80 silver badges100 bronze badges asked Nov 20, 2013 at 23:56 ThomasDThomasD 2,4947 gold badges40 silver badges58 bronze badges 0
Add a comment  | 

4 Answers 4

Reset to default 13

Your code does work (once you fix the syntax errors in the object array): http://jsfiddle.net/ArPCa/

var cars = [{ name:"Toyota Minivan", id:"506"}, { name:"Honda Civic", id:"619"}];
var x =!!_.where(cars, {id:'506'}).length;
console.log('value: ' + x);

returns "value: true". So there must be a problem somewhere else.

But, a better way to do this might be some:

var y = _.some(cars, function(c) {
    return c.id == '506'; 
});

I know this is late, but even easier:

var cars = [{ name:"Toyota Minivan", id:"506"}, { name:"Honda Civic", id:"619"}];

function findById(id) {
  return _.contains(_.pluck(cars, 'id'), id);
}

Say you have the array arr, and your id, id.

arr.filter(function(elem) { return elem.id == id; });

will return an array with the matching element(s);

You could wrap it in a function like:

function findById(arr, id) {
 var filtered = arr.filter(function(elem) { return elem.id == id; });
 return filtered && filtered.length ? filtered[0] : null;
}

, potentially doing some other stuff if you weren't happy with the default filtered array.

var obj = [{
    name: "Toyota Minivan",
    id: "506"
}, {
    name: "Honda Civic",
    id: "619"
}];

function findCar(id) {
    return obj.filter(function (car) {
        if (car.id == id) {
            return car;
        }
    });
}
发布评论

评论列表(0)

  1. 暂无评论