0

Super new to JavaScript, but if I have If JSON payload looked like this:

{
'ProcessID' : '234928734'
    'Steps' :
      0 : {
              'Thisthing' : 'Hello'
              'Thatthing' : 'Yeah'
             }
       1 : {
              'Thisthing' : 'UseMe'
              'Thatthing' : 'ReturnMe'
             }
}

I want my javascript function to return the words "ReturnMe" because the parameter 'Thisthing' = 'UseMe'. I don't the values of 'Thatthing' returned unless the 'Thisthing' is 'UseMe'. I've tried JSON.parse() but I can only get the root values.

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
mraguda
  • 35
  • 5
  • it looks like, you do not have a [JSON](https://json.org/) compliant string. just a plain object literal. please add your code. – Nina Scholz Oct 16 '20 at 21:36
  • If the JSON is valid and the syntax in the question is just some issue with how you chose to put it in the question, then this is related to https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json – Taplar Oct 16 '20 at 21:43
  • The proper JSON object you mean to show is probably: `{"ProcessID":"234928734","Steps":{"0":{"Thisthing":"Hello","Thatthing":"Yeah"},"1":{"Thisthing":"UseMe","Thatthing":"ReturnMe"}}}`. – iAmOren Oct 16 '20 at 21:59

1 Answers1

0

Here is a proposition:

  1. You must consider only the Steps object
  2. From that object keep only values (at this stage you've got an Array)
  3. Filter that array to keep only the object where 'Thisthing' === 'UseMe' (.filter returns an array of length === 1 hence the [0])
  4. Read the property 'Thatthing'

function findMe(data) {

    const steps = data.Steps; // (1)

    return Object.values(steps) // (2)
        .filter(obj => obj.Thisthing === 'UseMe')[0] // (3)
        .Thatthing; // (4)

}

console.log(findMe({
    'ProcessID': '234928734',
    'Steps': {
        0: {
            'Thisthing': 'Hello',
            'Thatthing': 'Yeah'
        },
        1: {
            'Thisthing': 'UseMe',
            'Thatthing': 'ReturnMe'
        }
    }
}));
Cedric Cholley
  • 1,956
  • 2
  • 9
  • 15