How to check the particular property exists in nested array object using javascript;
In the below arrobj
, if value
property is empty, remove and return the array of object
If all object property value is empty, return [];
using javascript.
var arrobj = [
{
id: 1,
task: [
{tid:1, value:[]},
{tid:2, value:[12,13]}
]
},
{
id: 2,
task: [
{tid:4, value:[14,15]}
]
}
]
Tried
var valueExists = arrobj.filter(e=>e.tasks.filter(i =>i.value.length > 0);
Expected Output:
[
{
id: 1,
task: [
{tid:2, value:[12,13]}
]
},
{
id: 2,
task: [
{tid:4, value:[14,15]}
]
}
]
>Solution :
Map the array, generate a new object for each enter. Filter the tasks and remove all tasks that have a length of 0. After mapping, filter it and remove all objects with empty task
array:
const filterTasks = arr => arr
.map(o => ({
...o,
task: o.task.filter(t => t.value.length)
}))
.filter(o => o.task.length)
const arr1 = [{"id":1,"task":[{"tid":1,"value":[]},{"tid":2,"value":[12,13]}]},{"id":2,"task":[{"tid":4,"value":[14,15]}]},{"id":3,"task":[{"tid":5,"value":[]}]}]
const arr2 = [ {"id":1,"task":[{"tid":1,"value":[]},{"tid":2,"value":[]}]}, {"id":2,"task":[{"tid":4,"value":[]}]}]
console.log(filterTasks(arr1))
console.log(filterTasks(arr2))