Home > Software design >  Map through array of arrays, to find id and change object
Map through array of arrays, to find id and change object

Time:05-25

I have an array of ids ['id1', 'id3'].

I also have an array of items:

[
      {
        children: [{
                  children: [{
                            id: "id1", //This is value I need to find
                            status: { state: false}, //this is value I need to change
                            }],
                  }],
      },
      {
        children: [{
                  children: [{
                            id: "id2", 
                            status: { state: false}, 
                            }],
                  }],
      },
      {
        children: [{
                  children: [{
                            id: "id3", 
                            status: { state: false}, 
                            }],
                  }],
      },
    ]

My goal is to find every item by id from first array, and change attribute state, then return all items having included those I have changed.

This was my try, but it returns all items again, also Im not sure how to change the attribute.

items.filter(item =>
  item.children.map(child =>
     child.children.map(object =>
        idsArray.map(id => id === object.id)
)))

CodePudding user response:

I think you can use recursive function something like below :

let ids = ["id1", "id2"];
let arrayOfItems = [
  {
    children: [
      {
        children: [
          {
            id: "id1",
            status: {
              state: false
            }
          }
        ]
      }
    ]
  },
  {
    children: [
      {
        children: [
          {
            id: "id2",
            status: {
              state: false
            }
          }
        ]
      }
    ]
  },
  {
    children: [
      {
        children: [
          {
            id: "id3",
            status: {
              state: false
            }
          }
        ]
      }
    ]
  }
];

function changeStatus(arrayOfItems, ids) {
  return arrayOfItems.map((e) => {
    if (e.id && ids.includes(e.id)) {
      return { ...e, status: { state: true } };
    } else if (e.children) {
      return { ...e, children: changeStatus(e.children, ids) };
    } else {
      return { ...e };
    }
  });
}

console.log(changeStatus(arrayOfItems,ids));

  • Related