0

I am using angular to fetch data from API which has some values as null, I want to change this values to an empty string.

sample JSON from API

[
    {
        "id": 84,
        "employee_name": "Alan",
        "phone_number": "",
        "process": null,
        "joining_date": null
    },
    {
        "id": 85,
        "employee_name": "Bob",
        "phone_number": "",
        "process": {
            "id": 1,
            "process_name": "Moulding"
        },
        "joining_date": null
    },
]

I have successfully changed these null values to an empty string while displaying them in a material table. But that means repeating the same code many times, so I want to do this transformation at a higher level i.e. on an HTTP get request.

api get request

public getAll(): Observable<any[]> {
   return this.http.get<any[]>(`${this.apiURL}/${this.specificURL}/`);
  }

I think it can be done using rxjs 'map' operator but I really don't know how to do it.

2
  • 1
    combine it with pipe(map(res =>.....)); Commented Nov 12, 2019 at 12:49
  • Which all fields can come as null? Just process and joining_date? Commented Nov 12, 2019 at 12:58

2 Answers 2

1

Here is a solution using map and Object.keys() to process all properties. You should modify your service like:

return this.http.get<any[]>(`${this.apiURL}/${this.specificURL}/`).pipe(map(res => mapNullProperties(res));

function mapNullProperties(data) {

  return data.map(objWithNull => {
    const objWithoutNull = {...objWithNull};
    Object.keys(objWithoutNull).forEach(key => {
      if (objWithoutNull[key] === null) {
        objWithoutNull[key] = '';
      }
    });
    return objWithoutNull;
  });
}

console.log(getAll([
    {
        "id": 84,
        "employee_name": "Alan",
        "phone_number": "",
        "process": null,
        "joining_date": null
    },
    {
        "id": 85,
        "employee_name": "Bob",
        "phone_number": "",
        "process": {
            "id": 1,
            "process_name": "Moulding"
        },
        "joining_date": null
    },
]));

Sign up to request clarification or add additional context in comments.

Comments

1

I wouldn't process the data and replace the value from null to ''.

What I would do is use || operator like this: {{joining_date || ''}} in the template where you show your value, so if it is null, the empty string will be used.

Comments

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.