Quick question, I want to return the object with id: 123
from the current array of objects:
[
{
name: nancy,
id: 999
},
{
name: kim,
id: 123
},
{
name: tess,
id: 888
}
]
Any id how to do that?
Quick question, I want to return the object with id: 123
from the current array of objects:
[
{
name: nancy,
id: 999
},
{
name: kim,
id: 123
},
{
name: tess,
id: 888
}
]
Any id how to do that?
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>
You can do it like this:
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));