D
D
Danil Samusev2020-09-09 13:25:57
JavaScript
Danil Samusev, 2020-09-09 13:25:57

How to remove null from JSON?

Null appears in json when deleting or adding new data.

It looks like this:
[{"test":-212}, null, {"test":-121}]

Delete via splice()
Add new data via push()

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Danil Samusev, 2020-09-12
@danilka238

Found a way.

//Подготовим массив для тестирования
var myArray = [1111, 5, 3, 4, null, undefined, 4, 5, null, 5];
//Удаляем  все элементы, равные undefined и null
myArray = myArray.filter(function(x) {
    return x !== undefined && x !== null; 
});
console.log(myArray.toString()); //1111,5,3,4,4,5,5

A
Aetae, 2020-09-09
@Aetae

Check what you add before push, obviously.

A
Argentinium, 2020-09-09
@Argentinium

You can use filter. Then a new array will be created without the old element, which can be dumped into JSON without garbage.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question