angular filter nested array

4255 views arrays
0

Hi I am developing web application in AngualarJS 5. I have one array and I am trying to update same array based on the input received. Below is my array.

[
 {
  checked:false,
  id:1109376510842,
  name:"info model",
  children:
  [
   {
     checked:false,
     id:5763308644187,
     name:'Configmodel'
   },
   {
     checked:false,
     id:5763308655187,
     name:'Devicemodel'
   }
  ]
 },
 {
  checked:false,
  id:1109376580842,
  name:"data access",
  children:
  [
   {
     checked:false,
     id:57633458644187,
     name:'Configmodel'
   },
   {
     checked:false,
     id:57633084555187,
     name:'Devicemodel'
   }
  ]
 }
]

I have one more input array which gives few details. Based on that array I want to update my parent array. My input object gives below details.

{
  parent: info model,
  data:{
  checked:true,
  id:5763308644187,
  name:'Configmodel'
  }
}

So based on the above object, I want to update my parent object. My object contains parent, this indicates which object from parent array has to be updated. Also object contains checked inside children. Now its true so I want to update checked inside children in info model of parent table. Can someone help me to fix this? Thanks

answered question

Can you show us code, what you have tried so far?

1 Answer

9

I hope I understand you correctly. You can do following in a service oder component:

updateObject(fullDataArray, updateObj) {
    // Find the parent 
    const parent = fullDataArray.find(e => e.name === updateObj.parent);

    // If the parent is set, search for the respective child entry
    if (parent) {
        const child = parent.children.find(e => e.id === updateObj.data.id);

        if (child) {
            // Updates the childs checked attribute
            child.checked = updateObj.data.checked;
        } else {
            // Add child if not exist
            parent.children.push(updateObj.data);
        }
    }

}

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories