Skip to content
JsDevLife
Menu
  • Home
  • Leetcode in JS
  • About me
  • Contact Us
Menu

Mastering in Javascript | Find Value in an array Object

Posted on January 9, 2019 by Vikas Kad

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

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

console.log(searchIndex)
>>>Output>>>>
1

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

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Solving LeetCode Problem 79 – Word Search in JavaScript
  • Solving LeetCode Problem 48: Rotate Image using JavaScript
  • Solving the “Container With Most Water” LeetCode Problem in JavaScript – A Comprehensive Guide
  • LeetCode Solution: 54: Spiral Matrix in JavaScript
  • Solution to LeetCode Problem 31. Next Permutation in JavaScript

Archives

  • 2023 (5)
  • 2022 (20)
  • 2021 (2)
  • 2020 (4)
  • 2019 (14)
  • 2018 (17)

Categories

  • blockchain development
  • Blog
  • crystal
  • flutter
  • flutter.io
  • GitHub
  • Installation
  • Ionic Framework
  • javascript
  • leetcode-in-js
  • masteringInJavasript
  • mcqs
  • MongoDB
  • nodejs
  • Object Oriented Javacript
  • python
  • smart contracts
  • visual studio

Quick Links

  • Home
  • Leetcode in JS
  • About me
  • Contact Us

Terms of service

  • Terms Of Service
  • Disclaimer
©2023 JsDevLife | Design: Newspaperly WordPress Theme