I have an an array of objects that contains a bunch of entires, but I want to group together some of them dynamically.
My Object could look like this
[{
Beton: "120"
Asfalt: "80"
ConstructionId: "(10)4"
Name: "Pælefundamenter og brøndfundamenter"
ParentId : "10"
ParentName: "Bygningsbasis, terræn"
}]
so now i want the object to look like this
[{
ConstructionId: "(10)4"
Name: "Pælefundamenter og brøndfundamenter"
ParentId : "10"
ParentName: "Bygningsbasis, terræn"
materialLifeTime: {
Beton: "120",
Asfalt: "80",
}
}]
I have tried a bunch, but can't make it work.
Thank you so much, Sillas
CodePudding user response:
You can try this .
const value = [{
Beton: "120",
Asfalt: "80",
ConstructionId: "(10)4",
Name: "Pælefundamenter og brøndfundamenter",
ParentId : "10" ,
ParentName: "Bygningsbasis, terræn"
}]
value[0].materialLifeTime = {
Beton: "120",
Asfalt: "80",
}
console.log(value )
CodePudding user response:
I think @Tvde1 is right. You can do this.
const materialLifeTime = [{
Beton: "120",
Asfalt: "80",
ConstructionId: "(10)4",
Name: "Pælefundamenter og brøndfundamenter",
ParentId : "10" ,
ParentName: "Bygningsbasis, terræn",
}]
const mainArrayObj = [{
ConstructionId: "(10)4",
Name: "Pælefundamenter og brøndfundamenter",
ParentId : "10" ,
ParentName: "Bygningsbasis, terræn",
}]
let modifiedArr = mainArrayObj.map(function(element){
const newArr = [element, {materialLifeTime: materialLifeTime}];
console.log(newArr);
});
let anotherWay = mainArrayObj.map(function(element){
const newArr = [element, ...materialLifeTime];
console.log(newArr);
});
CodePudding user response:
You can use delete()
to remove the keys from the original object
const data = [{
Beton: "120",
Asfalt: "80",
ConstructionId: "(10)4",
Name: "Pælefundamenter og brøndfundamenter",
ParentId : "10" ,
ParentName: "Bygningsbasis, terræn"
}];
const keysToMove = [ 'Asfalt', 'Beton' ];
const res = data.map(d => {
d.materialLifeTime = {};
keysToMove.forEach(k => {
d.materialLifeTime[k] = d[k];
delete d[k]
});
return d;
})
console.log(res);