txen
txen

Reputation: 135

Javascript check if values exist in array json

I want to check if my ids exist in an array list. I tried some, like IndexOf or hasOwnProperty and more.

Hope someone can help me.

Thats my try

if(array.hasOwnProperty('3771245')) {
    alert('is in array');
} else {
    alert('is not in array');
}

Thats the array:

var array = [ 
  {
    id: 3771245,
    sku: 149
  }, 
  { 
    id: 125125125,
    sku: 149
  },
  { 
    id: 5351531,
    sku: 149
  }
];

And below are my items I want to check if they are in the array json

var items = [ { id: '3771245' }, { id: '37712415' } ];

Upvotes: 0

Views: 2396

Answers (7)

Vadim
Vadim

Reputation: 8779

If you expect a simple true/false as a result, your function may look like this:

var array = [ 
  { id: 3771245,   sku: 149 }, 
  { id: 125125125, sku: 149 },
  { id: 5351531,   sku: 149 }
];

function checkIds(arr, ids) {
  return ids.every(id => (id = parseInt(id.id,10)) && arr.some(item => item.id === id))
}

console.log('All ids exist:', checkIds(array, [{id:'3771245'}, {id:'5351531'}]))

console.log('Not all ids exist:', checkIds(array, [{id:'3771245'}, {id:'5351532'}]))

While most of already posted solutions are functionally correct, I would recommend:

  • don't use map(...) on large list of ids to find, since even if first id does not exist, you'll still iterate over all objects containing ids and map them to some other values that will not be used;
  • don't use forEach(...) for the same reason
  • don't use filter(...) to avoid extra type casting and memory allocation for resulting array
  • if you know that all your ids are integers, cast to integer instead of string before compare values
  • don't use Number(...) - it will create an object of type Number and implicitly cast it to plain number every time it's compared to other value

Upvotes: 0

connexo
connexo

Reputation: 56754

Use Array.prototype.filter(), then Array.prototype.map():

var array = [{
    id: 3771245,
    sku: 149,
  },
  {
    id: 125125125,
    sku: 149,
  },
  {
    id: 5351531,
    sku: 149,
  }
]

const searchIds = [3771245, 125125125];

const items = array
  .filter(i => searchIds.includes(i.id))
  .map((i) => { return { id: i.id } })

console.log(items)

Upvotes: 1

brk
brk

Reputation: 50291

You can use Array.some function and check if an value from item array exists in array. It will return a Boolean depending on which you can create an object

var array = [{
    id: 3771245,
    sku: 149,
  },
  {
    id: 125125125,
    sku: 149,
  },
  {
    id: 5351531,
    sku: 149,
  }
]
var items = [{
  id: '3771245'
}, {
  id: '37712415'
}]

let ifExist = {};

items.forEach(function(item) {
  let __exist = array.some(function(elem) {
    return +item.id === elem.id

  })
  ifExist[item.id] = __exist
})

console.log(ifExist)

Upvotes: 0

Kudlas
Kudlas

Reputation: 659

    var array = [ { id: 3771245,
    sku: 149,
     }, 
     { id: 125125125,
    sku: 149,
     },
     { id: 5351531,
    sku: 149,
     }]
     
// usage
let index = findById(array, 3771245);
if(index!==false) {
	console.log("found in array on: ", index);
}


function findById(arr, id) {

	let exists = false;
	arr.forEach(function(element, i) {
  console.log(i);
  if(element.id==id) {
  	exists=i;
  }
});
	return exists;
}

I believe this is function you are looking for.

Upvotes: 0

Alexandru Cumpanici
Alexandru Cumpanici

Reputation: 21

Something like this should do the trick. If the list of items is short you can use this approach.

var array = [ { id: 3771245,
    sku: 149,
     }, 
     { id: 125125125,
    sku: 149,
     },
     { id: 5351531,
    sku: 149,
     }]
let values;
for(let i =0; i <array.length; i++){
      if(array[i].id.toString() === "125125125"){
      values=values+array[i].id.toString()+', ';
      }
}

Upvotes: 0

Madhan Varadhodiyil
Madhan Varadhodiyil

Reputation: 2116

You can split the search string by , and find the elements matching the search items

var array = [ { id: 3771245,
sku: 149,
 }, 
 { id: 125125125,
sku: 149,
 },
 { id: 5351531,
sku: 149,
 }];
 var items = '3771245,5351531';
items = items.split(',');
var matchedItems = [];
items.forEach(function(item){
var data = array.find( function( ele ) { 
    return ele.id == item;
} );
if(data){
matchedItems.push(data);
}

});
console.log(matchedItems);

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can split the comma separated value and loop over to it to check the id value against the object inside the array. Note that the id is numeric so you need to prefix the value with + or use parseInt() to change that to number and check it inside the find() function. You can also use ECMAScript but that will not work in IE and old browsers.

var array = [{
    id: 3771245,
    sku: 149,
  },
  {
    id: 125125125,
    sku: 149,
  },
  {
    id: 5351531,
    sku: 149,
  }
]
var items = [ { id: '3771245' }, { id: '37712415' } ];
var match = true;
items.forEach(function(itemObj){
  var exist = array.find(function(obj){
    return obj.id === parseInt(itemObj.id);
  });
  if(!exist){
    match = false;
  }
});
if(match){
  alert('All matched');
} else {
  alert('Not matched');
}

Upvotes: 0

Related Questions