This is the array object currently am working on an angular project
{
"DATA": [
{
"CUSTOM1": [
{
"value": "Item1",
"isSelected": true
},
{
"value": "Item2",
"isSelected": true
},
{
"value": "Item2",
"isSelected": false
},
{
"value": "Item3",
"isSelected": false
}
],
CUSTOM2": [
{
"value": "Item11",
"isSelected": true
},
{
"value": "Item12",
"isSelected": true
},
{
"value": "Item13",
"isSelected": false
},
{
"value": "Item14",
"isSelected": false
}
]
}
]
}
i wanted to update isSelected as false from CUSTOM1
How to do that in typescrpit
Expected a better solution
Thanks in advance
CodePudding user response:
run the following code:
let data = {
"DATA": [
{
"CUSTOM1": [
{
"value": "Item1",
"isSelected": true
},
{
"value": "Item2",
"isSelected": true
},
{
"value": "Item2",
"isSelected": false
},
{
"value": "Item3",
"isSelected": false
}
],
"CUSTOM2": [
{
"value": "Item11",
"isSelected": true
},
{
"value": "Item12",
"isSelected": true
},
{
"value": "Item13",
"isSelected": false
},
{
"value": "Item14",
"isSelected": false
}
]
}
]
};
data.DATA[0].CUSTOM1.forEach((val) => val.isSelected = false);
CodePudding user response:
The code you provided looks like a JSON string. You will first need to convert it to an JavaScript object.
Then you can loop the DATA
array to get to each CUSTOM1
. Then update isSelected
property to false
.
// I shortened your example down for simplicity.
const jsonString = `{"DATA": [{ "CUSTOM1": [{ "value": "Item1", "isSelected": true}]}]}`
const parsedJson = JSON.parse(jsonString);
const data = parsedJson.DATA;
data.forEach(d =>
d.CUSTOM1.forEach(c1 => c1.isSelected = false)
);
Most of the time, these strings are returned from back-end APIs. We already know the shape of the returned object. It's best to create a type
or interface
for it. The reason why we use TypeScript
is that we can leverage the type system.
type CUSTOM1 = {
value: string;
isSelected: boolean;
};
type CUSTOM2 = {
value: string;
isSelected: boolean;
};
type DATA = {
custom1: CUSTOM1[];
custom2: CUSTOM2[];
};
const data: DATA[] = [
{
custom1: [
{ value: 'item1', isSelected: true }
],
custom2: [
{ value: 'item11', isSelected: false }
]
}
];