简体   繁体   English

Javascript检查数组json中是否存在值

[英]Javascript check if values exist in array json

I want to check if my ids exist in an array list. 我想检查我的ID是否存在于数组列表中。 I tried some, like IndexOf or hasOwnProperty and more. 我尝试了一些,例如IndexOf或hasOwnProperty等。

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 下面是我要检查的项目是否在数组json中

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

Use Array.prototype.filter() , then Array.prototype.map() : 使用Array.prototype.filter() ,然后使用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) 

You can split the comma separated value and loop over to it to check the id value against the object inside the array. 您可以分割逗号分隔的值并循环到该值,以对照数组内的对象检查id值。 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. 请注意, id是数字,因此您需要在值前加上+或使用parseInt()将其更改为数字并在find()函数中进行检查。 You can also use ECMAScript but that will not work in IE and old browsers. 您也可以使用ECMAScript但在IE和旧版浏览器中将无法使用。

 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'); } 

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); 

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()+', ';
      }
}

  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. 我相信这是您正在寻找的功能。

You can use Array.some function and check if an value from item array exists in array . 您可以使用Array.some功能,并检查的值item数组中存在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) 

If you expect a simple true / false as a result, your function may look like this: 如果期望结果是简单的true / false ,则函数可能如下所示:

 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; 不要在大量ID上使用map(...)来查找,因为即使第一个ID不存在,您仍然会遍历所有包含ID的对象,并将它们映射到其他将不使用的值;
  • don't use forEach(...) for the same reason 出于相同的原因不要使用forEach(...)
  • don't use filter(...) to avoid extra type casting and memory allocation for resulting array 不要使用filter(...)以避免对结果数组进行额外的类型转换和内存分配
  • if you know that all your ids are integers, cast to integer instead of string before compare values 如果您知道所有ID都是整数,则在比较值之前将其转换为整数而不是字符串
  • 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 不要使用Number(...) -它将创建Number类型的对象,并在每次与其他值进行比较时将其隐式转换为纯数字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM