Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return arraobject if the particular property exists in nested array object using javascript;

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 [];

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading