I am very new to javascript and wondering how we can remove the null values from the javascript object without altering the structure of it ?
[
{
"name": [
"Chris"
],
"data": [
[
1293733800000,
2041.8391
],
null,
[
1301509800000,
891.194800000001
],
null,
[
1309372200000,
1040.9923
]
]
},
{
"name": "Mike",
"data": [
null,
[
1301509800000,
4465
],
null,
[
1309372200000,
4538
],
null,
[
1317321000000,
3700
],
null
]
}
]
Desired Output:
[
{
"name": [
"Chris"
],
"data": [
[
1293733800000,
2041.8391
],
[
1301509800000,
891.194800000001
],
[
1309372200000,
1040.9923
]
]
},
{
"name": "Mike",
"data": [
[
1301509800000,
4465
],
[
1309372200000,
4538
],
[
1317321000000,
3700
]
]
}
]
I have tried this function but it is altering the structure of object with adding index alternatively in each section :-
function removeEmpty(obj) {
return Object.fromEntries(
Object.entries(obj)
.filter(([_, v]) => v != null)
.map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v])
);
}
CodePudding user response:
You can try this:
const data = [{
"name": [
"Chris"
],
"data": [
[
1293733800000,
2041.8391
],
null, [
1301509800000,
891.194800000001
],
null, [
1309372200000,
1040.9923
]
]
},
{
"name": "Mike",
"data": [
null, [
1301509800000,
4465
],
null, [
1309372200000,
4538
],
null, [
1317321000000,
3700
],
null
]
}
]
const withOutNull = data.map(data => ({
...data,
data: data.data.filter(data => data !== null)
}))
console.dir(withOutNull)
CodePudding user response:
You could check the values of the object and filter only the first level of found arrays.
const
data = [{ name: ["Chris"], data: [[1293733800000, 2041.8391], null, [1301509800000, 891.194800000001], null, [1309372200000, 1040.9923]] }, { name: "Mike", data: [null, [1301509800000, 4465], null, [1309372200000, 4538], null, [1317321000000, 3700], null] }],
result = data.map(o => Object.fromEntries(Object
.entries(o)
.map(([k, v]) => [k, Array.isArray(v)
? v.filter(e => e !== null)
: v
])
));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
Assuming your original array is called data you can just do
const data2 = data.map(x => {
x.data = x.data.filter(y => y != null)
return x;
})
CodePudding user response:
Here I created the function with input for you:
const input = [
{"name": ["Chris"],"data": [[1293733800000,2041.8391],null,[1301509800000,891.194800000001],null,[1309372200000,1040.9923]]},{"name": "Mike","data": [null,[1301509800000,4465],null,[1309372200000,4538],null,[1317321000000,3700],null]}]
function removeNulls(input) {
input.forEach(obj => {
obj.data = obj.data.filter(arr => (arr !== null))
})
return input
}
console.log(removeNulls(input))