1

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"}]
2

1 Answer 1

1

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));
}
Sign up to request clarification or add additional context in comments.

8 Comments

What is def? Do you mean function?
Javascript for-in is not like PHP foreach. o is the key, not the element.
@Barmar - was in Python mode there for a bit. Thx.
thank you so much - solution 2 is working great for the most part. I do have a small hiccup tho. When I clear cache & session data the sessionStorageData key 'people' has a value of '[null]' which is causing the following error: Cannot read property 'catalogNumber' of null
ok updated answer. Added a filter to remove all "null/undefined" array elements.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.