1

I have an array of Object like

  [
      {
        "parentId": "uniqueParentId1",
        "parentName": "Parent1",
        "childProp1": "test1",
        "childProp2": "test3"
      },
      {
        "parentId": "uniqueParentId2",
        "parentName": "Parent2",
        "childProp1": "somevals",
        "childProp2": "other vals"
      }
      {
        "parentId": "uniqueParentId2",
        "parentName": "Parent2",
        "childProp1": "somevals 1",
        "childProp2": "other vals 1"
      }
    ]

and I want to combine it based in parentId and create an array of Object like below in Javascript . How can I do it ?

    [
      {
        "id": "uniqueParentId1",
        "name": "Parent1",
        "children": [
          {
            "childProp1": "test1",
            "childProp2": "test3"
          }
        ]
      },
      {
        "id": "uniqueParentId2",
        "name": "Parent2",
        "children": [
          {
            "childProp1": "somevals",
            "childProp2": "other vals"
          },
          {
            "childProp1": "somevals 1",
            "childProp2": "other vals 1"
          }
        ]
      }
    ]

The idea to convert flat object to nested Object is so that I can use the nested Object in Iterations easiely

4 Answers 4

1

You can do it with javascript easily. Create and make new array according to your old array.

var oldArray = [
    {
        "parentId": "uniqueParentId1",
        "parentName": "Parent1",
        "childProp1": "test1",
        "childProp2": "test3"
    },
    {
        "parentId": "uniqueParentId2",
        "parentName": "Parent2",
        "childProp1": "somevals",
        "childProp2": "other vals"
    },
    {
        "parentId": "uniqueParentId2",
        "parentName": "Parent2",
        "childProp1": "somevals 1",
        "childProp2": "other vals 1"
    }
];

var newArray = [];

for (var i = 0; i < oldArray.length; i++) {
    var currentObject = newArray.filter(function (x) { return x.id == 
oldArray[i].parentId })[0];
    if (currentObject == null) {
        var newObj = {
            id: oldArray[i].parentId,
            name: oldArray[i].parentName,
            children: [
                {
                    childProp1: oldArray[i].childProp1,
                    childProp2: oldArray[i].childProp2
                }
            ]
        };
        newArray.push(newObj)
    }
    else {
        currentObject.children.push({
            childProp1: oldArray[i].childProp1,
            childProp2: oldArray[i].childProp2
        });
    }
}
console.log(newArray); // your array is here
Sign up to request clarification or add additional context in comments.

Comments

0

You can do it like this: loop through your array and create a new array with the data you need, i didn't know what the name variable was supposed to be so i generated it.. if that is supposed to be the parentId number you can extract the digits from o.parentId I've also assumed that except parentId all other object keys are childs...

let arr = [{
    "parentId": "uniqueParentId1",
    "childProp1": "test1",
    "childProp2": "test3"
  },
  {
    "parentId": "uniqueParentId2",
    "childProp1": "somevals",
    "childProp2": "other vals"
  },
  {
    "parentId": "uniqueParentId2",
    "childProp1": "somevals 1",
    "childProp2": "other vals 1"
  }
];


let combined = {};
let parentid = 1;
let childs = {};
arr.map(o => {
  if (!combined[o.parentId]) {
    combined[o.parentId] = {
      id: o.parentId,
      name: "Parent" + parentid,
      children: []
    };
    parentid++;
  }
  childs = {}
  for (const [key, value] of Object.entries(o)) {
    if (key !== 'parentId') childs[key] = value;
  }
  combined[o.parentId].children.push(childs);
});
console.log(combined)

Comments

0

You can do:

const flatObjects = [{parentId: 'uniqueParentId1',parentName: 'Parent1',childProp1: 'test1',childProp2: 'test3',},{parentId: 'uniqueParentId2',parentName: 'Parent2',childProp1: 'somevals',childProp2: 'other vals',},{parentId: 'uniqueParentId2',parentName: 'Parent2',childProp1: 'somevals 1',childProp2: 'other vals 1'}]

const result = Object.values(
  flatObjects.reduce((a, c) => {
    const k = `${c.parentId}|${c.parentName}`
    a[k] = a[k] || {
      id: c.parentId,
      name: c.parentName,
      children: [],
    }
    a[k].children.push({
      childProp1: c.childProp1,
      childProp2: c.childProp2,
    })
    return a
  }, {})
)

console.log(result)

Comments

0

You can use a map data structure to store childrens of same parent, then conevert the map into Array.

const array = [{
        "parentId": "uniqueParentId1",
        "parentName": "Parent1",
        "childProp1": "test1",
        "childProp2": "test3"
    },
    {
        "parentId": "uniqueParentId2",
        "parentName": "Parent2",
        "childProp1": "somevals",
        "childProp2": "other vals"
    },
    {
        "parentId": "uniqueParentId2",
        "parentName": "Parent2",
        "childProp1": "somevals 1",
        "childProp2": "other vals 1"
    }
]
let map = new Map();
array.forEach((item) => {
    if (map.has(item.parentId)) {
        map.get(item.parentId).children.push({
            "childProp1": item.childProp1,
            "childProp2": item.childProp2
        })
    } else {
        map.set(item.parentId, {
            "id": item.parentId,
            "name": item.parentName,
            children: [{
                "childProp1": item.childProp1,
                "childProp2": item.childProp2
            }]
        })
    }
})
let result = [];
map.forEach((value)=>{
  result.push(value)
})
console.log(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.