How do you check if a value is present in an array of objects javascript?

I've assumed that ids are meant to be unique here. some is a great function for checking the existence of things in arrays:

const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];

function add[arr, name] {
  const { length } = arr;
  const id = length + 1;
  const found = arr.some[el => el.username === name];
  if [!found] arr.push[{ id, username: name }];
  return arr;
}

console.log[add[arr, 'ted']];

answered Apr 3, 2014 at 17:21

AndyAndy

56.7k12 gold badges64 silver badges91 bronze badges

8

This small snippets works for me..

const arrayOfObject = [{ id: 1, name: 'john' }, {id: 2, name: 'max'}];

const checkUsername = obj => obj.name === 'max';

console.log[arrayOfObject.some[checkUsername]]

if you have array of elements like ['john','marsh'] then we can do some thing like this

const checkUsername = element => element == 'john';
    
console.log[arrayOfObject.some[checkUsername]]

answered Jun 18, 2018 at 12:49

SagarSagar

3,9153 gold badges29 silver badges36 bronze badges

1

It's rather trivial to check for existing username:

var arr = [{ id: 1, username: 'fred' }, 
  { id: 2, username: 'bill'}, 
  { id: 3, username: 'ted' }];

function userExists[username] {
  return arr.some[function[el] {
    return el.username === username;
  }]; 
}

console.log[userExists['fred']]; // true
console.log[userExists['bred']]; // false

But it's not so obvious what to do when you have to add a new user to this array. The easiest way out - just pushing a new element with id equal to array.length + 1:

function addUser[username] {
  if [userExists[username]] {
    return false; 
  }
  arr.push[{ id: arr.length + 1, username: username }];
  return true;
}

addUser['fred']; // false
addUser['bred']; // true, user `bred` added

It will guarantee the IDs uniqueness, but will make this array look a bit strange if some elements will be taken off its end.

answered Apr 3, 2014 at 17:21

raina77owraina77ow

101k14 gold badges191 silver badges225 bronze badges

1

This is what I did in addition to @sagar-gavhane's answer

const newUser = {_id: 4, name: 'Adam'}
const users = [{_id: 1, name: 'Fred'}, {_id: 2, name: 'Ted'}, {_id: 3, name:'Bill'}]

const userExists = users.some[user => user.name === newUser.name];
if[userExists] {
    return new Error[{error:'User exists'}]
}
users.push[newUser]

Kamran

3731 gold badge4 silver badges15 bronze badges

answered Dec 18, 2019 at 9:49

2

There could be MULTIPLE POSSIBLE WAYS to check if an element[in your case its Object] is present in an array or not.

const arr = [
  { id: 1, username: 'fred' },
  { id: 2, username: 'bill' },
  { id: 3, username: 'ted' },
];

let say you want to find an object with id = 3.

1. find: It searches for an element in an array and if it finds out then it returns that element else return undefined. It returns the value of the first element in the provided array that satisfies the provided testing function. reference

const ObjIdToFind = 5;
const isObjectPresent = arr.find[[o] => o.id === ObjIdToFind];
if [!isObjectPresent] {            // As find return object else undefined
  arr.push[{ id: arr.length + 1, username: 'Lorem ipsum' }];
}

2. filter: It searches for elements in an array and filters out all element that matches the condition. It returns a new array with all elements and if none matches the condition then an empty array. reference

const ObjIdToFind = 5;
const arrayWithFilterObjects= arr.filter[[o] => o.id === ObjIdToFind];
if [!arrayWithFilterObjects.length] {       // As filter return new array
  arr.push[{ id: arr.length + 1, username: 'Lorem ipsum' }];
}

3. some: The some[] method tests whether at least one element is present in an array that passes the test implemented by the provided function. It returns a Boolean value. reference

const ObjIdToFind = 5;
const isElementPresent = arr.some[[o] => o.id === ObjIdToFind];
if [!isElementPresent] {                  // As some return Boolean value
  arr.push[{ id: arr.length + 1, username: 'Lorem ipsum' }];
}

answered Sep 3, 2020 at 4:26

DecPKDecPK

23k5 gold badges20 silver badges39 bronze badges

I think that, this is the shortest way of addressing this problem. Here I have used ES6 arrow function with .filter to check the existence of newly adding username.

var arr = [{
    id: 1,
    username: 'fred'
}, {
    id: 2,
    username: 'bill'
}, {
    id: 3,
    username: 'ted'
}];

function add[name] {
    var id = arr.length + 1;        
            if [arr.filter[item=> item.username == name].length == 0]{
            arr.push[{ id: id, username: name }];
        }
}

add['ted'];
console.log[arr];

Link to Fiddle

answered Jul 11, 2017 at 10:22

Kushan RandimaKushan Randima

2,0365 gold badges29 silver badges55 bronze badges

0

Let's assume we have an array of objects and you want to check if value of name is defined like this,

let persons = [ {"name" : "test1"},{"name": "test2"}];

if[persons.some[person => person.name == 'test1']] {
    ... here your code in case person.name is defined and available
}

answered Mar 31, 2020 at 9:11

Hasan ZahranHasan Zahran

1,24614 silver badges13 bronze badges

2

try this

first method using some

  let arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
    let found = arr.some[ele => ele.username === 'bill'];
    console.log[found]

second method using includes, map

   let arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
    let mapped = arr.map[ele => ele.username];
    let found = mapped.includes['bill'];
    console.log[found]

answered Feb 20, 2020 at 16:24

Trilok SinghTrilok Singh

1,06911 silver badges8 bronze badges

2

You could prototype your array to make it more modular, try something like this

    Array.prototype.hasElement = function[element] {
        var i;
        for [i = 0; i < this.length; i++] {
            if [this[i] === element] {
                return i; //Returns element position, so it exists
            }
        }

        return -1; //The element isn't in your array
    };

And you can use it as:

 yourArray.hasElement[yourArrayElement]

answered Nov 4, 2015 at 19:11

Luis SarazaLuis Saraza

1962 silver badges10 bronze badges

Accepted answer can also be written in following way using arrow function on .some

 function checkAndAdd[name] {
     var id = arr.length + 1;
     var found = arr.some[[el] => {
           return el.username === name;
     }];
     if [!found] { arr.push[{ id: id, username: name }]; }
 }

answered Sep 5, 2018 at 17:10

Hemadri DasariHemadri Dasari

30.5k33 gold badges113 silver badges152 bronze badges

Here is an ES6 method chain using .map[] and .includes[]:

const arr = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]

const checkForUser = [newUsername] => {
      arr.map[user => {
        return user.username
      }].includes[newUsername]
    }

if [!checkForUser['fred']]{
  // add fred
}
  1. Map over existing users to create array of username strings.
  2. Check if that array of usernames includes the new username
  3. If it's not present, add the new user

answered Apr 28, 2020 at 5:51

Len JosephLen Joseph

1,2639 silver badges20 bronze badges

I like Andy's answer, but the id isn't going to necessarily be unique, so here's what I came up with to create a unique ID also. Can be checked at jsfiddle too. Please note that arr.length + 1 may very well not guarantee a unique ID if anything had been removed previously.

var array = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' } ];
var usedname = 'bill';
var newname = 'sam';

// don't add used name
console.log['before usedname: ' + JSON.stringify[array]];
tryAdd[usedname, array];
console.log['before newname: ' + JSON.stringify[array]];
tryAdd[newname, array];
console.log['after newname: ' + JSON.stringify[array]];

function tryAdd[name, array] {
    var found = false;
    var i = 0;
    var maxId = 1;
    for [i in array] {
        // Check max id
        if [maxId 

Chủ Đề