-1

I am new to JavaScript and am looking for a way to: first, extract values from a desired key in a complex JSON object. Second, if the value does not equal a given string, print the parent key. Here is a simplified JSON object that needs to be parsed. There are many more entries in the file.

{
    "Test1": {
        "protocolName": "Test1",
        "createdAsProtocolName": "AnalyticsTest1",
        "message": "Protocol already exists!",
        "importStatus": "success",
        "protocolApplicationName": "Flexi-Protocol",
        "protocolId": 1,
        "applicationId": 5
    },
    "Test2": {
        "protocolName": "Test2",
        "createdAsProtocolName": "AnalyticsTest2",
        "message": "Protocol already exists!",
        "importStatus": "success",
        "protocolApplicationName": "Flexi-Protocol",
        "protocolId": 2,
        "applicationId": 5
    },
    "Test3": {
        "protocolName": "Test3",
        "createdAsProtocolName": "AnalyticsTest3",
        "message": "Error",
        "importStatus": "failed",
        "protocolApplicationName": "Flexi-Protocol",
        "protocolId": 3,
        "applicationId": 5
    },
    "Test4": {
        "protocolName": "Test4",
        "createdAsProtocolName": "AnalyticsTest4",
        "message": "Error",
        "importStatus": "failed",
        "protocolApplicationName": "Flexi-Protocol",
        "protocolId": 4,
        "applicationId": 5
    }
}

I want to check each test's ['importstatus'] for "success" and if any say otherwise, save them in an array ["Test3", "Test4"]

Defqon
  • 117
  • 11
  • 2
    What have you already researched and/or tried? – PM 77-1 Sep 15 '22 at 19:16
  • To be clear, is this coming to you as a string (JSON)? Or as an Object? – mykaf Sep 15 '22 at 19:18
  • That makes no sense. [JSON](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) is a string. – mykaf Sep 15 '22 at 19:21
  • @PM77-1 I can loop through and grab every keys value or I can access each value directly by hardcoding obj["Test1"]["importStatus"] but that obviously won't work when I have a couple hundred entries – Defqon Sep 15 '22 at 19:21
  • Does this help? [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) – mykaf Sep 15 '22 at 19:22
  • 1
    Does this answer your question? [How to loop through a plain JavaScript object with the objects as members](https://stackoverflow.com/questions/921789/how-to-loop-through-a-plain-javascript-object-with-the-objects-as-members) – PM 77-1 Sep 15 '22 at 19:23

1 Answers1

2

For each key/value pair in yourObject, filter out any with importStatus of success, and return the keys of the rest.

const arrayOfFailures = Object.entries(yourObject)
  .filter(([k, v]) => v.importStatus !== "success")
  .map(([k, v]) => k);
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
James
  • 20,957
  • 5
  • 26
  • 41