dealing-with-json-responses

Dealing with JSON Responses and optional properties

by

Josoroma

Once you go with Lodash, you’ll never go back and _.has() and _.get() are coming under the spotlight to prove my point.

As you probably already know, the _.has() method takes two parameters, the first one is an object that we are pretty sure exists and the second one represents the rest of the path we are looking. This path may or may not exist, if it does not exist, it will return false.

But I’m not here to talk about the _.has() method; the reason of this post belongs to the awesome _.get() method.

_.get()

_.get() method returns the value, if the property does not exist, returns undefined. We can optionally pass a value in the event one does not exist.

const records = [
    {
        id: 1,
        type: 'Friend',
        project: {
            startDate: '2016-08-30',
            country: {
                name: 'Costa Rica'
            }
        }
    },
    {
        id: 2,
        type: 'Friend'
    }
];

const result = records.map(record => {
    record.id               = _.get(record, 'id', null);
    record.type             = _.get(record, 'type', null);
    record.projectStartDate = _.get(record, 'project.startDate', null);
    record.projectCountry   = _.get(record, 'project.country.name', null);

    delete record.project;

    return record;
});

console.log(result);

Result

[
    {
        "id": 1,
        "type": "Friend",
        "projectStartDate": "2016-08-30",
        "projectCountry": "Costa Rica"
    },
    {
        "id": 2,
        "type": "Friend",
        "projectStartDate": null,
        "projectCountry": null
    }
]

Summary

The recipe is: If You are playing with a single logical AND, You should go for the _.has() method. Basically, _.get() can save our day or part of it if we are dealing with optional or missing properties from JSON Responses (REST Services).

Comments

comments

Powered by Facebook Comments