0

I have this array:

[
  {
    "name": "Homer Simpson",
    "age": "43",
    "start_time": null,
    "end_time": null
  },
  {
    "name": "Bart Simpson",
    "age": "14",
    "start_time": "2023-11-10T20:08:10Z",
    "end_time": "2023-11-10T20:08:10Z"
  }
];

How do I omit the start_time and end_time from each object if the value is NULL? I would like to end with this array:

[
  {
    "name": "Homer Simpson",
    "age": "43"
  },
  {
    "name": "Bart Simpson",
    "age": "14",
    "start_time": "2023-11-10T20:08:10Z",
    "end_time": "2023-11-10T20:08:10Z"
  }
];

I know I can loop through each object and push into a new array with the omitted values if the time values are null, but is there a more concise way of doing it? Is there a way I can use Array.filter?

0

1 Answer 1

1

Simple way to do this is to use mapping with lodash pickBy function.

It's a bit shorter and more elegant than using reduce.

Reference

import {map, pickBy} from 'lodash';

const data = [
  {
    "name": "Homer Simpson",
    "age": "43",
    "start_time": null,
    "end_time": null
  },
  {
    "name": "Bart Simpson",
    "age": "14",
    "start_time": "2023-11-10T20:08:10Z",
    "end_time": "2023-11-10T20:08:10Z"
  }
];

const result = map(data, obj => pickBy(obj, (value, key) => value !== null));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.