1

I have two array something like this

array1 = [
    {
        Name: "BMW car",
        id: "BMW",
        group: "car",
        children: [
            { Name: "320 Mod", id: "320", group: "BMW" },
            { Name: "X3 Mod", id: "X3", group: "BMW" },
            { Name: "X5 Mod", id: "X5", group: "BMW" }
        ]
    }
];

array2 = [
    {
        id: "BMW",
        description: "parent car BMW",
        children: [
            { id: "320", description: "parent car BMW, model 320", },
            { id: "X3", description: "parent car BMW model X3", },
            { id: "X5", description: "parent car BMW Model X5", }
        ]
    }
];

The result array should be something like this below

arrayObj = [
    {
        Name: "BMW car",
        id: "BMW",
        group: "car",
        description: "parent car BMW",
        children: [
            { Name: "320 Mod", id: "320", group: "BMW", description: "parent car BMW model 320", },
            { Name: "X3 Mod", id: "X3", group: "BMW", description: "parent car BMW model X3", },
            { Name: "X5 Mod", id: "X5", group: "BMW", description: "parent car BMW model X5", }
        ]
    }
];

I have tried below code but the children value doesn't get merged. Can any one please help me

var resultArray = array1.reduce((arr, e) => {
    arr.push(Object.assign({}, e, array2.find(a => a.id == e.id)))
    return arr;
}, [])

1 Answer 1

1

You could use this

var array1 = [
    {
        Name: "BMW car",
        id: "BMW",
        group: "car",
        children: [
            { Name: "320 Mod", id: "320", group: "BMW" },
            { Name: "X3 Mod", id: "X3", group: "BMW" },
            { Name: "X5 Mod", id: "X5", group: "BMW" }
        ]
    }
];

var array2 = [
    {
        id: "BMW",
        description: "parent car BMW",
        children: [
            { id: "320", description: "parent car BMW, model 320", },
            { id: "X3", description: "parent car BMW model X3", },
            { id: "X5", description: "parent car BMW Model X5", }
        ]
    }
];

var result = array1.map(el1 => {
  var el2 = array2.find(el => el1.id === el.id);
  return { ...el1, ...el2, children: el1.children.map(child1 => ({ ...child1, ...el2.children.find(child2 => child2.id === child1.id) })) };
});

console.log(result);

Sign up to request clarification or add additional context in comments.

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.