JavaScript Solutions, Competitive programming in JavaScript, MCQ in JS

Wednesday, 9 January 2019

Mastering in Javascript | Find Value in an array Object

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}

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:

Find value in an array of object

Now if we use ES6 then our code will be only one line which as follows:

let ob = arrObj.find(obj => === 'Rahul');

{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.

var searchIndex = arrObj.findIndex(x => == 'Rahul')


So as you have seen the code you can easily get value from an array of object.

No comments:

Post a Comment