0

This is my json data and i wanted to remove the category with null value from my json.

I mean not to delete the "Category":"start" but delete "Category":null.
I have seen some answers regarding this but it deletes all the category including "Category":"start" which I do not want.

"First": [{
        "category": "Start",
        "name": "Start",
        "key": 1,
        "lastname": "xyz"
    }, {
        "category": null,
        "text": "Step",
        "key": 2,
        "lastname": "xyz"
    }, {
        "category": null,
        "text": "Condition",
        "key": 3,
        "loc": "xyz"
    }
Ricky
  • 488
  • 3
  • 14
  • Loop through the array, check if the `category` is `null` (eg `obj === null`), and if so, `delete` it from the object. Capitalization matters, you say `"Category":"start"` but have `"category": "start"`, make sure to use the same capitalization – CertainPerformance May 31 '19 at 06:48
  • why you want to remove it from JSON, I assume you are using this JSON somewhere, you need to just use the one with ` "category" : "start" ' and ignore the others. Might be I can give you better answer, if you tell what you want to do? – Zabih Ullah May 31 '19 at 06:51
  • yeah,You said right but i am going to use it for some predefined api modification and for me it is not possible to do the same from that side .So i am going this way. Thanks @ZabihUllah – Ricky May 31 '19 at 06:56

2 Answers2

1

See the code below. This will give you the output you expect.

const array = [{
  "category": "Start",
  "name": "Start",
  "key": 1,
  "lastname": "xyz"
}, {
  "category": null,
  "text": "Step",
  "key": 2,
  "lastname": "xyz"
}, {
  "category": null,
  "text": "Condition",
  "key": 3,
  "loc": "xyz"
}];

const list = array.map(item => {
  let object = item;
  [undefined, null].includes(object.category) && delete object.category;
  return object;
});

console.log(list);
Ken Labso
  • 885
  • 9
  • 13
  • 1
    I have used the answer provided by Maheer Ali but your answer is also usefull ,Thanks a lot@Ken Ryan Labso – Ricky May 31 '19 at 07:43
1

You can use map() and destructuring of parameters of the function.

const arr = [{ "category": "Start", "name": "Start", "key": 1, "lastname": "xyz" }, { "category": null, "text": "Step", "key": 2, "lastname": "xyz" }, { "category": null, "text": "Condition", "key": 3, "loc": "xyz" } ]

const res = arr.map(({category,...rest}) => category === null ? {...rest} : {category,...rest})
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • In the similar way if i want to add a new attribute say where "key":"2" what should i do??@Maheer Ali – Ricky May 31 '19 at 07:50