Mastering in Javascript:
As the title suggests I am going to write one new series for mastering in javascript, here I will write some useful tips and tricks which will help you to write better code.
Find value in an array of object
Let’s take an example as follows:
let arrObj = [
{ id:201,name:"Vikas", age:27},
{ id:204, name:"Rahul", age:25}
];
let arrObj = [
{ id:201,name:"Vikas", age:27},
{ id:204, name:"Rahul", age:25}
];
Now you have arrObj and you want to check whether Rahul name is present or not and return that object from an array.
Now we will see it with looping to find the value.
function search(name, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === name) {
return myArray[i];
}
}
}
var resultObject = search("Rahul", array);
The output will be as follows:
Now if we use ES6 then our code will be only one line which as follows:
let ob = arrObj.find(obj => obj.name === 'Rahul');
console.log(ob);
>>>Output>>>>
{id: 204, name: "Rahul", age: 25}
But if you want to find the index of the value then you can use the following code to find the index of it.
function search(name, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === name) {
return myArray[i];
}
}
}
var resultObject = search("Rahul", array);
let ob = arrObj.find(obj => obj.name === 'Rahul');
console.log(ob);
>>>Output>>>>
{id: 204, name: "Rahul", age: 25}
var searchIndex = arrObj.findIndex(x => x.name == 'Rahul')
console.log(searchIndex)
>>>Output>>>>
1
>>>Output>>>>
1