DekGenius.com
JAVASCRIPT
javascript find object by property in array
// To find a specific object in an array of objects
myObj = myArrayOfObjects.find(obj => obj.prop === 'something');
find object in array javascript with property
let obj = objArray.find(obj => obj.id == 3);
find object in array by property javascript
// Find an object with a given property in an array
const desiredObject = myArray.find(element => element.prop === desiredValue);
search an array of objects with specific object property value
// MDN Ref:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
var result = jsObjects.find(obj => {
return obj.b === 6
});
javascript find object in array by property value
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
const filterItems = (needle, heystack) => {
let query = needle.toLowerCase();
return heystack.filter(item => item.toLowerCase().indexOf(query) >= 0);
}
console.log(filterItems('ap', fruits)); // ['apple', 'grapes']
console.log(filterItems('ang', fruits)); // ['mango', 'orange']
search an array of objects with specific object property value
var result = jsObjects.find(obj => {
return obj.b === 6
})
Find an object in an array by one of its properties
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function isCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }
Find object by any property
// Sample array
var myArray = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Peter"},
{"id": 3, "name": "Harry"}
];
// Get the Array item which matchs the id "2"
var result = myArray.find(item => item.id === 2);
console.log(result.name); // Prints: Peter
// Get the index of Array item which matchs the id "2"
var index = myArray.findIndex(item => item.id === 2);
console.log(index); // Prints: 1
console.log(myArray[index].name); // Prints: Peter
© 2022 Copyright:
DekGenius.com