简体   繁体   中英

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. 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.

Solution #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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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