Q:

find in array of objects javascript

const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'cherries', quantity: 8}
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
  {name: 'cherries', quantity: 15}
  
];

const result = inventory.find( ({ name }) => name === 'cherries' );

console.log(result) // { name: 'cherries', quantity: 5 }
11
var result = jsObjects.find(obj => {
  return obj.b === 6
})
2
let arr = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

let obj = arr.find(o => o.name === 'string 1');

console.log(obj);
2
// To find a specific object in an array of objects
myObj = myArrayOfObjects.find(obj => obj.prop === 'something');
9
var __POSTS = [ 
	{ id: 1, title: 'Apple', description: 'Description of post 1' }, 
	{ id: 2, title: 'Orange', description: 'Description of post 2' }, 
	{ id: 3, title: 'Guava', description: 'Description of post 3' }, 
	{ id: 4, title: 'Banana', description: 'Description of post 4' }
];

var __FOUND = __POSTS.find(function(post, index) {
	if(post.title == 'Guava')
		return true;
});

// On success __FOUND will contain the complete element (an object)
// On failure it will contain undefined  
console.log(__FOUND); // { id: 3, title: 'Guava', description: 'Description of post 3' }
1
//The find() method returns the value of the first element in the provided array that satisfies the provided testing function.
const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12
2
let arr = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

let obj = arr.find((o, i) => {
    if (o.name === 'string 1') {
        arr[i] = { name: 'new string', value: 'this', other: 'that' };
        return true; // stop searching
    }
});

console.log(arr);
1
myArray.findIndex(x => x.id === '45');
0
myArray.find(x => x.id === '45').foo;
0

New to Communities?

Join the community