0

I Used the following code to append my json structured values to a state variable:

var value = JSON.stringify({"id":event.target.name,"amount":event.target.value})

this.setState({temp:[...this.state.temp, value]},function () {
    console.log(this.state.temp);
}); 

And i got the result as:

["{"id":"1","amount":"10"}","{"id":"2","amount":"20"}"]

How can i get it restructured as following:

[{"id":"1","amount":"10"},{"id":"2","amount":"20"}]

Update: When i removed JSON.stringify like this var value = {"id":event.target.name,"amount":event.target.value} i got null array as result

2
  • Remove JSON.stringify(...) Commented Feb 21, 2018 at 12:37
  • Don't stringify the JS object Commented Feb 21, 2018 at 14:21

4 Answers 4

2

That is because you are using stringify on value (object), that will return a string, then you are pushing that string into state array.

Avoid stringify and directly push that object.

Like this:

var value = {"id": event.target.name, "amount": event.target.value};

this.setState(
    prevState => ({ temp: [...prevState.temp, value] }), 
    () => { console.log(this.state.temp);}
);

Suggestion:

Use updater function instead of using this.state inside setState method.

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

7 Comments

@Mayank This gives a null array as result
what is the initial value of temp? also you are using same value as i pasted in the snippet?
Initial value of temp is null
it should be [], as per my knowledge it should throw error if the initial value is null, check console are you getting any error?
I have given as temp: [] in my state initialisation and not null. I just meant null array as []
|
0

Try this one, no need to use JSON.stringify

var value = {"id":event.target.name,"amount":event.target.value}
    this.setState({temp:[...this.state.temp, value]},function () {
         console.log(this.state.temp);
    }); 

2 Comments

This gives a null array as result
plz change temp = [] as @mayank suggest. that was the issue.
0

JSON.stringify creates a string from JS object. That is why all object is surrounded by quotes within an array.

Try this.

var value = {"id":event.target.name,"amount":event.target.value};

this.setState({temp:[...this.state.temp, value]},function () {
  console.log(this.state.temp);
});

Comments

0

Option 1: remove the

var value = JSON.stringify({"id":event.target.name,"amount":event.target.value});

Option2: use:

JSON.parse(value);

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.