0

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?

4
  • Is this array of objects (it's not JSON) part of your this.state? Commented May 30, 2018 at 9:09
  • @T.J.Crowder yep, actually I've parse JSON from API, and I got those Array when console.log Commented May 30, 2018 at 9:10
  • But is it part of your this.state? Commented May 30, 2018 at 9:11
  • Please read What is the difference between JSON and Object Literal Notation? Commented May 30, 2018 at 9:11

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.