Home > front end >  How do I compare two array of objects and create new array if condition matches
How do I compare two array of objects and create new array if condition matches

Time:04-05

I would like to compare objects in an array and create a new

I would like to have a new Array of Objects created when

  • phaseID in parentArr matches the PhaseID in childArr

In this instance the new object should push the child details along with the parent details

I have used Map and Filter however didn't get the expected output.

Thanks

let parentArr = [
  {
    "phaseID": 1,
    "name": "S(Executive)"
  },
  {
    "phaseID": 2,
    "name": "p(Executive)"
  },
  {
    "phaseID": 3,
    "name": "pluto1(Executive)"
  }
]

let childArr = [
  {
    "childID": 1,
    "phaseID": 1,
    "name": "abc"
  },
  {
    "childID": 2,
    "phaseID": 1,
    "name": "efg"
  },
  {
    "childID": 3,
    "phaseID": 2,
    "name": "hij"
  }
]

The Expected output is below

let newArr = [
  {
    "phaseID": 1,
    "name": "S(Executive)",
    "childNode": [
      {
        "childID": 1,
        "name": "abc"
      },
      {
        "childID": 2,
        "phaseID": 1,
        "name": "efg"
      }
    ]
  },
  {
    "phaseID": 2,
    "name": "p(Executive)",
    "childNode": [
       {
          "childID": 3,
          "name": "hij"
       }
     ]
  },
  {
    "phaseID": 3,
    "name": "pluto1(Executive)"
  }
]

CodePudding user response:

If you want new array instead of updating existing parentArr, you can try this

function mapResult(parentArr, childArr) {
  const newArr = [];
  parentArr?.forEach(parentNode => {
    const result = {
      name: parentNode.name,
      phaseID: parentNode.phaseID,
      childNode: childArr?.filter(childNode => parentNode.phaseID == childNode.phaseID) || [],
    };
    newArr.push(result);
  });
  return newArr;
}

CodePudding user response:

You can define a simple mapping function that .maps the parent nodes and searches for childNodes by comparing the phaseID. If they match, push the childNode to the parentNode:

let parentArr = [{
    "phaseID": 1,
    "name": "S(Executive)"
}, {
    "phaseID": 2,
    "name": "p(Executive)"
}, {
    "phaseID": 3,
    "name": "pluto1(Executive)"
}]

let childArr = [{
    "childID": 1,
    "phaseID": 1,
    "name": "abc"
}, {
    "childID": 2,
    "phaseID": 1,
    "name": "efg"
}, {
    "childID": 3,
    "phaseID": 2,
    "name": "hij"
}]

function mapResult(parentArr, childArr) {
    const result = [];
    for(const parentNode of parentArr){
        const currNode = {...parentNode};
        for (const childNode of childArr) {
            if (childNode.phaseID === currNode.phaseID) {
                currNode.childNode = currNode.childNode || [];
                const {childID, name} = childNode;
                currNode.childNode.push({childID, name});
            }
        }
        result.push(currNode);
    }
    return result;
}

console.log(mapResult(parentArr, childArr));

  • Related