well my Question is : how can i group some items from an object in new array filed
for Exemple :
myArray = [
{ Name: "Alex", Age :"13" , Email: " Alex @gmail.com" },
{ Name: "Eva", Age :"24", Email: " Eva @gmail.com" },
{ Name: "Adem", Age :"60", Email: " Adem @gmail.com" },
{ Name: "Jack", Age :"20", Email: " Jack @gmail.com" }
]
The result that i want is :
myArray = [
{ Name: "Alex", Details: [{ Age: "13", Email: " Alex @gmail.com" }] },
{ Name: "Eva", Details :[{ Age: "24", Email :" Eva @gmail.com" }] },
{ Name: "Adem", Details :[{ Age: "60", Email :" Adem @gmail.com" }] },
{ Name: "Jack", Details :[{ Age: "20", Email :" Jack @gmail.com" }]}
]
CodePudding user response:
try that
const
myArray = [
{ Name:"Alex", Age:"13" , Email:" Alex @gmail.com" },
{ Name:"Eva", Age:"24", Email:" Eva @gmail.com" },
{ Name:"Adem", Age:"60", Email:" Adem @gmail.com" },
{ Name:"Jack", Age:"20", Email:" Jack @gmail.com" }
]
, newArray = myArray.map(({Name, ...others})=>({Name, Details:[{...others}]}))
console.log(newArray)
CodePudding user response:
myArray = [
{Name:"Alex", Age:"13" , Email:" Alex @gmail.com"},
{Name:"Eva", Age:"24", Email:" Eva @gmail.com" },
{Name:"Adem", Age:"60", Email:" Adem @gmail.com"},
{Name:"Jack", Age:"20", Email:" Jack @gmail.com"}
]
const newArray = myArray.map(i => {
return {Name: i.Name, Details: [{Age: i.Age, Email: i.Email}]}
})
console.log(newArray)
CodePudding user response:
//use this you will get the exact result
myArray = [
{Name: "Alex", Age :"13" , Email :" Alex @gmail.com"},
{Name: "Eva", Age :"24", Email :" Eva @gmail.com"},
{Name: "Adem", Age :"60", Email :" Adem @gmail.com"},
{Name: "Jack", Age :"20", Email :" Jack @gmail.com"}
]
newArray = [];
for(let details of myArray) {
let groupedInfo = {Details: []};
let groupedDetails = {}
for(let info in details) {
if(info == 'Name') {
groupedInfo[info] = details[info];
}
else {
groupedDetails[info] = details[info];
}
}
groupedInfo['Details'].push(groupedDetails);
newArray.push(groupedInfo);
}
console.log(newArray);