I've an array of objects. I want don't want to render duplicates array but I want it's items to be merged with it's same one which is render example shown below.
Original Array
array = [
{
name: 'Test',
items: [
{
id: 1,
product_name: "Kbana 1",
},
{
id: 2,
product_name: "Kbana 2",
},
]
},
{
name: 'Test 2',
items: [
{
id: 3,
product_name: "Kbana 3",
},
{
id: 4,
product_name: "Kbana 4",
},
]
},
{
name: 'Test 2',
items: [
{
id: 5,
product_name: "Kbana 5",
},
{
id: 6,
product_name: "Kbana 6",
},
]
},
]
Now I have two same array objects which index is 1 and 2. Now I wants to merge index 2 items values with index 1. Like example below
array = [
{
name: 'Test',
items: [
{
id: 1,
product_name: "Kbana 1",
},
{
id: 2,
product_name: "Kbana 2",
},
]
},
{
name: 'Test 2',
items: [
{
id: 3,
product_name: "Kbana 3",
},
{
id: 4,
product_name: "Kbana 4",
},
{
id: 5,
product_name: "Kbana 5",
},
{
id: 6,
product_name: "Kbana 6",
},
]
}
]
var arr = [
{
name: 'Test',
items: [
{
id: 1,
product_name: "Kbana 1",
},
{
id: 2,
product_name: "Kbana 2",
},
]
},
{
name: 'Test 2',
items: [
{
id: 3,
product_name: "Kbana 3",
},
{
id: 4,
product_name: "Kbana 4",
},
]
},
{
name: 'Test 2',
items: [
{
id: 5,
product_name: "Kbana 5",
},
{
id: 6,
product_name: "Kbana 6",
},
]
},
]
const newArr = [];
for(var i = 0;i<arr.length;i++)
{
var name = arr[i].name;
for(var j = 0;j<arr.length;j++)
{
if(i != j)
{
if(name === arr[j].name)
{
arr[i].items = [...arr[i].items, ...arr[j].items]
arr[j].name = "remove";
}
}
}
}
arr = arr.filter(data => data.name !== "remove");
console.log(arr);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments