Quantcast
Channel: How do I check if an array includes a value in JavaScript? - Stack Overflow
Viewing all articles
Browse latest Browse all 66

Answer by Shiva for How do I check if an array includes a value in JavaScript?

$
0
0

Simple solution for this requirement is using find()

If you're having array of objects like below,

var users = [{id: "101", name: "Choose one..."},
{id: "102", name: "shilpa"},
{id: "103", name: "anita"},
{id: "104", name: "admin"},
{id: "105", name: "user"}];

Then you can check whether the object with your value is already present or not

let data = users.find(object => object['id'] === '104');

if data is null then no admin, else it will return the existing object like below.

{id: "104", name: "admin"}

Then you can find the index of that object in the array and replace the object using below code.

let indexToUpdate = users.indexOf(data);
let newObject = {id: "104", name: "customer"};
users[indexToUpdate] = newObject;//your new object
console.log(users);

you will get value like below

[{id: "101", name: "Choose one..."},
{id: "102", name: "shilpa"},
{id: "103", name: "anita"},
{id: "104", name: "customer"},
{id: "105", name: "user"}];

hope this will help anyone.


Viewing all articles
Browse latest Browse all 66

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>