查找具有特定键值对的JS对象/哈希

Ric*_*ard 0 javascript jquery ruby-on-rails

假设我有一个JS对象,其中包含多个具有相同属性的对象.

编辑:我将外括号修改为方括号以反映实际对象是什么.接受的答案在评论中.

var object = [
   {
      id: 1,
      foo: 'bar'
   },
   {
      id: 2,
      foo: 'bar2'
   },
   {
      id: 3,
      foo: 'bar3'
   },
   {
      id: 4,
      foo: 'bar4'
   }
];
Run Code Online (Sandbox Code Playgroud)

我如何获得具有特定id的对象,例如id == 1类似于Rails方法的东西ActiveRecord::Relation.where(id: 1)

Roh*_*mar 6

你需要为搜索创建一个对象数组,试试这个,

var object = [{ // make array by using [ and ]
    id: 1,
    foo: 'bar'
}, {
    id: 2,
    foo: 'bar2'
}, {
    id: 3,
    foo: 'bar3'
}, {
    id: 4,
    foo: 'bar4'
}];
function searchByKey(obj, key) {
    for (var i in obj) {
        if (obj[i].id == key) {
            return obj[i];
        }
    }
    return "Not found";
}
console.log(searchByKey(object,1));
console.log(searchByKey(object,4));
Run Code Online (Sandbox Code Playgroud)

现场演示