I have an array of object and it looks like this, I want to remove attributeType object and get a new one. How can I delete object in array?
{
"id": 2,
"version": 1,
"name": "test",
"attributeInputs": {
"0": {
"id": 4,
"position": 0,
"label": "display",
"attributeType": {
"id": 3,
"label": "Input",
"fieldType": "TEXT"
},
},
"1": {
"id": 5,
"position": 3,
"label": "price",
"attributeType": {
"id": 5,
"label": "Price",
"fieldType": "PRICE"
},
}
}
}
I would like delete AttributeType and it should look like this:
{
"id": 2,
"version": 1,
"name": "test",
"attributeInputs": {
"0": {
"id": 4,
"position": 0,
"label": "display",
},
"1": {
"id": 5,
"position": 3,
"label": "price",
}
}
}
CodePudding user response:
You can use Object.keys()
on the attributeInputs
field and delete the key attributeType
:
const obj = {
"id": 2,
"version": 1,
"name": "test",
"attributeInputs": {
"0": {
"id": 4,
"position": 0,
"label": "display",
"attributeType": {
"id": 3,
"label": "Input",
"fieldType": "TEXT"
},
},
"1": {
"id": 5,
"position": 3,
"label": "price",
"attributeType": {
"id": 5,
"label": "Price",
"fieldType": "PRICE"
},
}
}
}
Object.keys(obj.attributeInputs).forEach(o => delete obj.attributeInputs[o].attributeType )
console.log(obj)
CodePudding user response:
first, let's store the object in a variable called myObject. now let's work on the variable myObject.
myObject.attributeInputs = Object.keys(myObject.attributeInputs).map(key=>{
const {attributeType,...newObj}=myObject.attributeInputs[key];
return newObj;
});
it's not clean code, but it works.