Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append JSON object to existing JSON object in JS file in react.js

I am trying to make a Todo app using React.js.

I took todo data from an in-app js file as a JSON object. I want to add more todo in my list which I want to store in that js file as a JSON object.

I want to append another JSON object with existing. How can I do it?

TodoList.js file

const TodoList=
   [

    {
      "id": 1,
      "title": "Learn backbone",
      "complete": false,
      "canceled": false,
      "date": new Date().getTime()
    },

    {
      "id": 2,
      "title": "Go for a run",
      "complete": false,
      "canceled": false,
      "date": new Date().getTime()
    }
  ]

  export default TodoList;

New TodoList.js file should be like this:

const TodoList=
[

    {
      "id": 1,
      "title": "Learn backbone",
      "complete": false,
      "canceled": false,
      "date": new Date().getTime()
    },

    {
      "id": 2,
      "title": "Go for a run",
      "complete": false,
      "canceled": false,
      "date": new Date().getTime()
    },

    {
      "id": 3,
      "title": "Have Lunch",
      "complete": true,
      "canceled": false,
      "date": new Date().getTime() 
    }
  ]

  export default TodoList
like image 752
Md. Hasan Uzzaman Avatar asked Oct 25 '25 00:10

Md. Hasan Uzzaman


1 Answers

This has nothing to do with React, this is plain object/array manipulation in Javascript. If you want to take an existing array and add a new element, simply have:

const newToDoList = [...toDoList, {"id": 3, ...}]

You spread the previous array and create a new one with a new element.

like image 144
Gilad Bar Avatar answered Oct 27 '25 14:10

Gilad Bar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!