Use the find()
method to find objects in the array by property value in JavaScript. As per definition.
The find()
method returns the first value in the array if an element in the array satisfies the provided testing function. Otherwise undefined
is returned.
myArray.find(x => x.id === '45');
If you want to find its index instead, use findIndex()
:
myArray.findIndex(x => x.id === '45');
JavaScript finds the object in the array by property value
Simple example code get object by id value from an array of objects.
<!DOCTYPE html>
<html>
<body>
<script>
var myArray = [{'id':'73','foo':'bar'},
{'id':'45','foo':'bar'}];
var res = myArray.find(x => x.id === '45');
console.log(res);
</script>
</body>
</html>
Output:
More example
var myArray = [
{id:1, name:"bob"},
{id:2, name:"dan"},
{id:3, name:"barb"},
]
// grab the Array item which matchs the id "2"
var item = myArray.find(item => item.id === 2);
// print
console.log(item.name);
Output: dan
Some options.
For loop:
function getByValue(arr, value) {
for (var i=0, iLen=arr.length; i<iLen; i++) {
if (arr[i].b == value) return arr[i];
}
}
.forEach
function getByValue3(arr, value) {
var result = [];
arr.forEach(function(o){if (o.b == value) result.push(o);} );
return result? result[0] : null; // or undefined
}
Filter
array of objects, which property matches value, returns an array:
var result = jsObjects.filter(obj => {
return obj.b === 6
})
Do comment if you have any doubts or suggestions on this JS object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version