Home > Net >  How to keep from each parent only children by id from object
How to keep from each parent only children by id from object

Time:10-04

I am trying to keep only children from each parent if it matches a child's id from a given list of parent/child ids.

var parentIds = ['1','2','3']; 
var childrenIds = ['2','3','5'];

Parent with id '1' should only have children with id '2', parent with id '2' should only have children with id '3' and parent with id '3' should only have children with id '5'. So, parent id matches children id in same position from both arrays.

Example of initial object:

var object = [
  {
    name: "parent1",
    id: 1,
    option_values: [
      {
        name: "child1",
        id: 1
      },
      {
        name: "child2",
        id: 2
      },
      {
        name: "child8",
        id: 8
      }
    ]
  },
  {
    name: "parent2",
    id: 2,
    option_values: [
      {
        name: "child3",
        id: 3
      },
      {
        name: "child1",
        id: 1
      },
      {
        name: "child9",
        id: 9
      }
    ]
  },
  {
    name: "parent3",
    id: 3,
    option_values: [
      {
        name: "child5",
        id: 5
      },
      {
        name: "child4",
        id: 4
      },
      {
        name: "child13",
        id: 13
      }
    ]
 },
 ]

Expected result:

var result = [
  {
    name: "parent1",
    id: 1,
    option_values: [
      {
        name: "child2",
        id: 2
      }
    ]
  },
  {
    name: "parent2",
    id: 2,
    option_values: [
      {
        name: "child3",
        id: 3
      }
    ]
  },
  {
    name: "parent3",
    id: 3,
    option_values: [
      {
        name: "child5",
        id: 5
      }
    ]
 },
 ]

CodePudding user response:

Loop through the objects. Find the index of the parent ID in the parentIds array, then get the corresponding element of childIds. Then filter the option_values array using that child ID.

var object = [{
    name: "parent1",
    id: 1,
    option_values: [{
        name: "child1",
        id: 1
      },
      {
        name: "child2",
        id: 2
      },
      {
        name: "child8",
        id: 8
      }
    ]
  },
  {
    name: "parent2",
    id: 2,
    option_values: [{
        name: "child3",
        id: 3
      },
      {
        name: "child1",
        id: 1
      },
      {
        name: "child9",
        id: 9
      }
    ]
  },
  {
    name: "parent3",
    id: 3,
    option_values: [{
        name: "child5",
        id: 5
      },
      {
        name: "child4",
        id: 4
      },
      {
        name: "child13",
        id: 13
      }
    ]
  },
];

var parentIds = ['1', '2', '3'];
var childrenIds = ['2', '3', '5'];

object.forEach(obj => {
  let idIndex = parentIds.indexOf(String(obj.id));
  if (idIndex != -1) {
    let childId = parseInt(childrenIds[idIndex]);
    obj.option_values = obj.option_values.filter(child => child.id == childId);
  }
});

console.log(object);

  • Related