Reputation: 1974
I have a JSON from API, the response of API is to declare if the task already done,
example of JSON :
[ { Name: 'Pre Operation', Checked: false },
{ Name: 'Operation', Checked: false },
{ Name: 'Post Operation', Checked: false } ]
How can I update a JSON to be like :
[ { Name: 'Pre Operation', Checked: true},
{ Name: 'Operation', Checked: false },
{ Name: 'Post Operation', Checked: false } ]
I have tried using this code:
var output = jsonResult.map((item)=>{
if(item.Checked == true){
item.Checked === false
}
return item
})
But the JSON doesnt change, and I'm afraid item.Checked === false
will effected all of item.Checked
that has true
value
and if I have a response from API like this:
[ { Name: 'Pre Operation', Checked: true},
{ Name: 'Operation', Checked: false },
{ Name: 'Post Operation', Checked: false } ]
I need to update a JSON to be like this:
[ { Name: 'Pre Operation', Checked: true},
{ Name: 'Operation', Checked: true},
{ Name: 'Post Operation', Checked: false } ]
Anyone can help me how to archieve my goal?
Upvotes: 0
Views: 1056
Reputation: 533
Not sure if I'm misunderstanding the question, but surely you can just..
jsonResult[0].Checked = true;
edit.. if you want to be less ruthless..
jsonResult.some((item) => { if (item.Name = 'Pre Operation') { item.Checked = true; return true; })
array.prototype.some is a good way to exist a loop when you've done what you need - once 'true' is returned it will stop looping.
Upvotes: 0
Reputation: 28445
Use Array.find
var arr = [ { Name: 'Pre Operation', Checked: false }, { Name: 'Operation', Checked: false }, { Name: 'Post Operation', Checked: false } ];
function updateStatus(){
var result = arr.find(({Checked}) => !Checked);
if(result) result.Checked = true;
}
updateStatus(); console.log(arr); // first is updated
updateStatus(); console.log(arr); // second is updated
updateStatus(); console.log(arr); // third is updated
updateStatus(); console.log(arr); // no update
Upvotes: 3