快速提问,我想从当前的对象数组中返回id: 123
的对象:
[
{
name: nancy,
id: 999
},
{
name: kim,
id: 123
},
{
name: tess,
id: 888
}
]
任何id怎么做?
答案 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)
你可以这样做:
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;