Shan-Desai
Shan-Desai

Reputation: 3349

Check if key exists in JSON response within map function

For instance, I receive a JSON response:

[
  {
    'key_1': 'value1A',
    'key_2': 'value2A',
    'key_3': 'value3A'
  },
  {
    'key_1': 'value1B',
    'key_2': 'value2B',
  }
]

As observed, key_3 wasn't provided in the second element of the array. Here the keys are the same for each object within the array.

Lets say, I am interested in only using key_2 and key_3 of the response and hence I use map as follows

this.serv.getInfo(code) // HTTP GET service
  .subscribe(res => {
    this.data = res.map(el => { // only use necessary key:value pairs
      let _out = { // make an object to return

        'new_key_1': el.key_2
        'new_key_2': '' // if there is no key_3 then leave it empty

      }
      if ('key_3' in el) { // if this pair exists then add it..

        _out['new_key_2'] = el.key_3
        return _out;

      }

      return _out; // if not return with empty string
    });
  });

This works well as the JSON Response is small in this case. But I assume the if(.. in el) checks may increase many fold if the JSON structure would be large and complex.

What operator would be best suited in this case for a more dynamic check when mapping the response to a new object. Is there even a necessity to create a temp _opt object within the map function?

Upvotes: 1

Views: 686

Answers (1)

Kristianmitk
Kristianmitk

Reputation: 4778

You could use el['key_3'] || '' which is known as Short-circuit evaluation.

DEMO

let data = [
  {
    'key_1': 'value1A',
    'key_2': 'value2A',
    'key_3': 'value3A'
  },
  {
    'key_1': 'value1B',
    'key_2': 'value2B',
  }
],
  arr = data.map((el) => {
    return {'key_1': el['key_2'], 'key_2': el['key_3'] || ''};
  });

console.log(arr);

However it does not cover cases where el['key_3'] equals null,undefined, false, 0.

If this is unacceptable, then the in operator is the only way to really determine if a key within an object exist. You could use it with a ternary operator and thus avoid the use of a temporary object - see demo

DEMO

let data = [
  {
    'key_1': 'value1A',
    'key_2': 'value2A',
    'key_3': 'value3A'
  },
  {
    'key_1': 'value1B',
    'key_2': 'value2B',
    'key_3': undefined,
  }
],
  arr = data.map((el) => {
    return {'key_1': el['key_2'], 'key_2': 'key_3' in el ? el['key_3'] : ''};
  });

console.log(arr);

Upvotes: 1

Related Questions