Find Object by Id in an Array of JavaScript Objects

Find object by id in an array of JavaScript objects

Use the find() method:

myArray.find(x => x.id === '45').foo;

From MDN:

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.


If you want to find its index instead, use findIndex():

myArray.findIndex(x => x.id === '45');

From MDN:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.


If you want to get an array of matching elements, use the filter() method instead:

myArray.filter(x => x.id === '45');

This will return an array of objects. If you want to get an array of foo properties, you can do this with the map() method:

myArray.filter(x => x.id === '45').map(x => x.foo);

Side note: methods like find() or filter(), and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel (with the polyfill).

Javascript check if object by Id is in array

let id = 3;
const arr = [{
id: 1,
name: 'James'
}, {
id: 2,
name: 'Peter'
}, {
id: 3,
name: 'Mike'
}]

var chek = arr.find(c => c.id === id);

console.log(chek ?? "Not present")
//or:
if (chek === undefined) {
console.log("Not present")
} else {
console.log(chek.name)
}

Find a value in an array of objects in Javascript

You can loop over the array and test for that property:

function search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}

var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];

var resultObject = search("string 1", array);

Find user details by ID in nested object nodejs | javascript

check this code.... Enter any id number

const data = [{
"service": [
"BUSINESS",
"LEGAL",
"FINANCE",
"ADVERTISEMENT"
],
"service1": [
{ "id": 1, "name": "a" },
{ "id": 2, "name": "b" },
{ "id": 3, "name": "c" },
{ "id": 4, "name": "d" },
],
"service2": [
{ "id": 5, "name": "e" },
{ "id": 6, "name": "f" },
{ "id": 7, "name": "g" },
{ "id": 8, "name": "h" },
],
"service3": [
{ "id": 9, "name": "i" },
{ "id": 10, "name": "j" },
{ "id": 11, "name": "k" },
{ "id": 12, "name": "l" },
],
"service4": [
{ "id": 13, "name": "m" },
{ "id": 14, "name": "n" },
{ "id": 15, "name": "o" },
{ "id": 16, "name": "p" },
],
}]
var itemobj = ''
const searchName =(val)=>{
console.log('searchname')
data.map((item)=>{
let obj = Object.keys(item)
obj.map((data)=>{
let inrdata = item[data]
inrdata.map((initem)=>{
let lastdata = initem.id===val?itemobj=initem:null


})

})
})
}

searchName(3)
console.log(itemobj)


Related Topics



Leave a reply



Submit