简体   繁体   English

如何使用jQuery搜索JSON?

[英]How can I search JSON with jQuery?

I'm using a session storage to temporarily hold data and try to search for a string ( CatalogNumber ) in the session data. 我正在使用会话存储临时存储数据,并尝试在会话数据中搜索字符串( CatalogNumber )。 If the string isn't existing I'd like to add it. 如果该字符串不存在,我想添加它。

This is what I've tried so far but it's still allowing duplicates. 到目前为止,这是我尝试过的方法,但仍允许重复。 And the search isn't working for the array for some reason: 由于某种原因,搜索不适用于该数组:

var gridData = {
    catalogNumber: dataItem.CatalogNumber,
    fullName: dataItem.FullName,
    position: dataItem.CurrentTitle
};

sessionStorageData = JSON.parse(sessionStorage.getItem('people'));

if (jQuery.inArray(gridData.catalogNumber, sessionStorageData ) === -1) {
    sessionStorageData.push(gridData);
    sessionStorage.setItem('people', JSON.stringify(sessionStorageData));
}

Data 数据

[{"catalogNumber":"51263bf7-83c4-e411-825d-28b2bd14ba94","fullName":"John Doe","position":"Receptionist"}]

It makes sense that the array search isn't working. 数组搜索无效是有道理的。

Your array is an array of objects. 您的数组是一个对象数组。 You are trying to match a string (in this case gridData.catalogNumber ) against those objects. 您正在尝试将一个字符串(在本例中为gridData.catalogNumber )与这些对象进行匹配。

Solution #1: 解决方案1:

If your array was an array of strings, then your search would work. 如果您的数组是字符串数组,则搜索将起作用。 An alternate approach might be: 一种替代方法可能是:

function found(gridData, sessionStorageData) {
  for (o in sessionStorageData) {
    if (sessionStorageData[o].catalogNumber == gridData.catalogNumber) {
      return true;
    }
  }
  return false;
}

if (!found(gridData.catalogNumber, sessionStorageData )) {
    sessionStorageData.push(gridData);
    sessionStorage.setItem('people', JSON.stringify(sessionStorageData));
}

Solution #2 解决方案#2

An even better solution might be to map your array of objects into an array of strings. 更好的解决方案可能是将对象数组映射为字符串数组。

var catalogNumbers = sessionStorageData.filter(function(obj){ return !!obj }).map(function(obj) { return obj.catalogNumber; } );
if (jQuery.inArray(gridData.catalogNumber, catalogNumbers ) === -1) {
    sessionStorageData.push(gridData);
    sessionStorage.setItem('people', JSON.stringify(sessionStorageData));
}

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

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