0

How to add new element to array with setState

I have this data

this.state = {
    items : [
   { "id" : "324", "parent" : "qqqq", "text" : "Simple root node" },
   { "id" : "24", "parent" : "dwdw", "text" : "Root node" },
   { "id" : "55", "parent" : "ajson2", "text" : "Ch" },
   { "id" : "9866", "parent" : "ajson2", "text" : "oiiojio" },
]
    }

I'm mapping the data

{this.state.items.sort((a,b) => a.newID < b.newID).map((item)=>
   <ul>
     <li key={item.id}><span>ID: </span>{item.id} <span>parent: </span>{item.parent} <span>text: </span>{item.text}</li>
   </ul>
   )}

and then I'm sorting the data by newID That I need to create it with setState

this.setState(prevState=>({newData: [...prevState.items, this.props.account.info]}));

How can I create new element with this.props.account.info add somthing like i++ I don't know actually

this.props.account.info It's adding data like

{ "id" : "324", "parent" : "qqqq", "text" : "Simple root node" }

So I need to add an element inside this will be like

{ "newID": "1", "id" : "324", "parent" : "qqqq", "text" : "Simple root node" }
2
  • "but this only sorting by ID, Do I add an element only for sorting" depends on your requirements, which we don't know. What should you sort for? Commented Feb 14, 2018 at 14:31
  • @FedericoklezCulloca I edited my question cus it wasn't clear enough Commented Feb 14, 2018 at 15:02

1 Answer 1

1

So if you want to add "newID" field in the object, there is a way to do this using object spread operator.

{...this.props.account.info, "newID":"1"}

This will give you a new object with the "newID" field added with "1" as its value associated with it.

This is a shorthand for this:

Object.assign({}, this.props.account.info, {"newID": "1"});
Sign up to request clarification or add additional context in comments.

1 Comment

This is not what I'm looking for, I need to add new ID element will gives deffrenet value for each item.

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.