I have this array of objects returned from server
{
"Code": 200,
"Message": "Success",
"response": [
{
"UserId": null,
"FullName": test,
"Status": null,
"IsActive": 1
},
{
"UserId": null,
"FullName": null,
"Status": 'Active',
"IsActive": 0
}...
...
]
}
getting response in List
variable
this.Service.getUser(payload).subscribe(result => {
this.List = result['response'];
});
i need some way to manipulate Status
value such as if Status is null
the assign it Active
value.
and again store it in this.List
variable without using any loop.
Please suggest some solution.
Thanks
CodePudding user response:
Since the response object is an Array
, you can just map
over it.
{...user}
will use all of properties of the existing object. Only Status
will be overwritten with the logic provided.
this.List = result['response'].map((user) => ({...user, Status: user.status === null ? 'Active' : user.status}));
You can not solve this issue without some kind of loop. That's the nature of an array.
CodePudding user response:
You can make use of map
here to loop over response
array and add State
as Active
if Status === null
const apiData = {
"Code": 200,
"Message": "Success",
"response": [{
"UserId": null,
"FullName": 'test',
"Status": null,
"IsActive": 1
},
{
"UserId": null,
"FullName": null,
"Status": 'Active',
"IsActive": 0
}
]
}
const result = apiData.response.map(o => ({ ...o, Status: o.Status ?? "Active" }));
console.log(result);