找到具有特定ID的正确对象

时间:2015-03-27 10:42:24

标签: javascript

快速提问,我想从当前的对象数组中返回id: 123的对象:

[
  {
    name: nancy,
    id: 999
  },
  {
    name: kim,
    id: 123
  },
  {
    name: tess,
    id: 888
  }
]

任何id怎么做?

2 个答案:

答案 0 :(得分:0)

var list = [{
  name: 'nancy',
  id: 999
}, {
  name: 'kim',
  id: 123
}, {
  name: 'tess',
  id: 888
}]

function findById(list, id) {
  var index = list.map(function(element) {
    return element.id
  }).indexOf(id)
  return list[index]
}

document.getElementById('result').innerHTML = JSON.stringify(findById(list, 123))
<pre>
  <p>result: <code id="result"></code>
</pre>

答案 1 :(得分:0)

你可以这样做:

&#13;
&#13;
var array = [{
  name: "nancy",
  id: 999
}, {
  name: "kim",
  id: 123
}, {
  name: "tess",
  id: 888
}];

function getObjectById(id) {
  for (var i = 0; i < array.length; i++) {
    if(array[i].id === id){
      return array[i];
    }
  }
};

alert(getObjectById(123));
&#13;
&#13;
&#13;