Insert an item into a convoluted array

I'm struggling to insert an Object into a complex array. My attempt looks like this: "DUMMY_PLACES[0].todos.byIds.push," but I am unable to make it work. I have an id and content for the object, and the completed property should default to false. I hope someone can help me with this seemingly simple task that I can't seem to figure out. Additionally, I would appreciate any assistance with implementing the delete option.

For example, I have (5, test5), and I want to achieve the desired outcome.

     const DUMMY_PLACES = [
          {
            todos: {
              allIds: [1, 2, 3, 4,],
              byIds: {
                "1": {
                  content: "test1",
                  completed: false,
                },
                "2": {
                  content: "test2",
                  completed: false,
                },
                "3": {
                  content: "test3\\",
                  completed: false,
                },
                "4": {
                  content: "test4",
                  completed: false,
                },
              },
            },
            visibilityFilter: "all",
          },
        ];

 const DUMMY_PLACES = [
      {
        todos: {
          allIds: [1, 2, 3, 4,5],
          byIds: {
            "1": {
              content: "test1",
              completed: false,
            },
            "2": {
              content: "test2",
              completed: false,
            },
            "3": {
              content: "test3\\",
              completed: false,
            },
            "4": {
              content: "test4",
              completed: false,
            },
            "5": {
              content: "test5",
              completed: false,
            },
          },
        },
        visibilityFilter: "all",
      },
    ];

Answer №1

Explore the addTodo function below, which adds a new element to the end of a new instance of the todoList and updates the list of Ids. Each line is extensively commented for easy understanding.

let todoList = [
  {
    todos: {
      allIds: [1, 2, 3, 4],
      byIds: {
        "1": {
          content: "test1",
          completed: false,
        },
        "2": {
          content: "test2",
          completed: false,
        },
        "3": {
          content: "test3",
          completed: false,
        },
        "4": {
          content: "test4",
          completed: false,
        },
      },
    },
    visibilityFilter: "all",
  },
];

let addTodo = (sourceArray, el) => {
  // Create a copy of the original array
  let targetArray = [];
  Object.assign(targetArray, sourceArray);

  let todos = targetArray[0].todos;

  // Calculate the Id for the new element
  let newId = Object.keys(todos.byIds).length + 1;

  // Add the new Id to the `allIds` list
  todos.allIds.push(newId);

  // Create the new element
  todos.byIds[newId] = {
    content: el,
    completed: false
  }

  return targetArray;
}

todoList = addTodo(todoList, 'test5');
todoList = addTodo(todoList, 'test6');
todoList = addTodo(todoList, 'test7');

console.log(JSON.stringify(todoList));

The expected output will be:

[
  {
    "todos":{
      "allIds":[
        1,
        2,
        3,
        4,
        5,
        6,
        7
      ],
      "byIds":{
        "1":{
          "content":"test1",
          "completed":false
        },
        "2":{
          "content":"test2",
          "completed":false
        },
        "3":{
          "content":"test3",
          "completed":false
        },
        "4":{
          "content":"test4",
          "completed":false
        },
        "5":{
          "content":"test5",
          "completed":false
        },
        "6":{
          "content":"test6",
          "completed":false
        },
        "7":{
          "content":"test7",
          "completed":false
        }
      }
    },
    "visibilityFilter":"all"
  }
]

Answer №2

Perhaps a solution like this could work for you

const DUMMY_PLACES = [ { todos: { allIds: [1, 2, 3, 4], byIds: { "1": { content: "test1", completed: false, }, "2": { content: "test2", completed: false, }, "3": { content: "test3\\", completed: false, }, "4": { content: "test4", completed: false, }, }, }, visibilityFilter: "all", }, ];

function addObject(id, content) {
  DUMMY_PLACES[0].todos.allIds.push(id);
  DUMMY_PLACES[0].todos.byIds[id] = { ...content, completed: false };
}
addObject(5, { content: "test5" });
console.dir(DUMMY_PLACES);

Answer №3

Your code could benefit from implementing encapsulation. A recommended approach would be to create a new class with setters.

UPDATE with an example:

class UserTodoList
{
    constructor( visibilityFilter = 'all' )
    {
        this._visibilityFilter  = visibilityFilter;
        this._todosByIds        = new Map();
    }

    addTodo( title, content )
    {
        const value = {
            content,
            completed: false
        }
        this._todosByIds.set( title, value );
    }

    getTodo( title )
    {
        return this._todosByIds.get( title );
    }

    completeTodo( title )
    {
        this._todosByIds.get( title ).completed  = true;
    }

    deleteTodo( title )
    {
        this._todosByIds.delete( title );
    }

    getAllTodoIds()
    {
        return Array.from( this._todosByIds.keys() );
    }

    getVisibilityFilter()
    {
        return this._visibilityFilter;
    }

    // Implement other getters
}

const TODO_LIST = [];
TODO_LIST.push( new UserTodoList( 'all' ) );

const todoTitle = 'Some Title';

TODO_LIST[0].addTodo( todoTitle, 'Do Something' );

console.log( TODO_LIST[0].getTodo( todoTitle ) );

TODO_LIST[0].completeTodo( todoTitle );

console.log( TODO_LIST[0].getTodo( todoTitle ) );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activate search bar by clicking on it

I am currently attempting a basic jQuery example to expand a search bar on mouse click, but for some reason, my code is not working as expected. I have a simple jQuery function to display the input field when the button with the class "expand" is clicked, ...

Eliminating the initial array to streamline the JSON output

I have a simple function that generates an array which can be easily "json_encoded." This function works well. However, I now need to repeat this process multiple times. while($row = mysql_fetch_assoc($resultsol)) { $all[] = jsonoutput("$row[appid]"); ...

When trying to reference "this" and store it in a variable, it appears as undefined. However, DevTools show that it is actually defined

I've encountered an unusual situation in my React app involving the binding of "this" - I have a function within a component named "App" that is located in a separate file. In the main file, I've bound the "this" command to it. What's puzzl ...

Scroll to the previous view with React

My task involves handling 10 lists of questions within a single multi-step form. I intend to address each question gradually, starting from the first one. Moreover, I aim to incorporate a feature where users can navigate back to the initial question by cl ...

Tips for managing the retrieval of non-existent images in JavaScript with LiipImagineBundle

I need to verify the existence of a file in NodeJS. While exploring a previous post, I came across this solution: const tryRequire = (path) => { try { return require(`${path}`); } catch (err) { return null; } }; However, is this the most ...

Error: Property 'onclick' cannot be set on a null object

JavaScript isn't my strong suit, so I'm struggling to solve this issue. The console is showing me the following error message: Uncaught TypeError: Cannot set property 'onclick' of null <script> var modal = document.getE ...

Discover how to display the loading time and memory usage of a web page on the footer using the jQuery and AngularJS library

Does anyone know how to display the loading time and memory usage of a web page in the footer using jQuery and AngularJS libraries? I've managed to show the loading time with this jQuery code: <script type="text/javascript"> before = (new Date( ...

Elements recognized worldwide, Typescript, and a glitch specific to Safari?

Consider a scenario where you have a select element structured like this: <select id="Stooge" name="Stooge"> <option value="0">Moe</option> <option value="1">Larry</option> <option value="2">Curly</option ...

"TypeScript Static Classes: A Powerful Tool for Struct

In my TypeScript code, there is a static class with an async build method as shown below: export default class DbServiceInit { public static myProperty: string; public static build = async(): Promise<void> => { try { ...

Issue encountered while retrieving JSON data from Github

I am currently using d3.json to retrieve a JSON link from the Enterprise GitHub (within the same repository/folder as the JavaScript file). d3.json("https://raw.github.exampleEnterprise.com/path/to/repo/data.json?token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ...

What are the two terms enclosed in brackets when using Matlab?

For what purpose is this syntax used? [sbox idx] = sort(box); Upon reviewing the information on Sorting array elements, I was anticipating to see something similar to: [sbox, idx] = sort(box); However, this is not the case based on the code provided (i ...

Toggle the Bootstrap navbar class based on the current scroll position

I'm currently working on the development of a website that includes a feature where a static navbar transforms into a fixed navbar after scrolling down 500px. The transition from "navbar-static-top" to "navbar-fixed-top" is functioning properly. Howev ...

Creating a fresh instance of an Object from a Service that leverages the $resource

I have been enhancing my existing code to improve its functionality by creating two objects for interacting with a RESTful API. Before, I utilized $http to retrieve the data and return the promise. I would then add some actions using .then and repeat the ...

The JavaScript code that added links to the mobile menu on smaller screens is no longer functioning properly

I recently created a website with a mobile navigation menu that should appear when the browser width is less than 1024px. However, I used some JavaScript (with jQuery) to include links to close the menu, but now the site is not displaying these links and t ...

Having difficulties linking the front end and the back end despite diligently following the tutorial

Currently, I am experimenting with creating a real-time chat application by following a tutorial on YouTube from JavaScriptMastery. The tutorial link is here, and the GitHub repository is available at this link. Despite closely mimicking the code displayed ...

Creating unique div IDs dynamically in PHP, JavaScript, and MySQL

I'm currently working with an ajax code that fetches data from table columns when a specific data is selected from the dropdown menu. In my surveycontent.php file, I have the following script: <script type="text/javascript"> function show ...

Incorporate user input into Alert Dialog Boxes

Would you be able to assist me in displaying the input value from the "email" field in my alert box? The code seems to be working fine, but I'm having trouble getting the alert box to show the email form value. I decided to use Bootstrap for som ...

Whenever I use NextJS's <Link> component, I always end up getting redirected to a

After searching online, I came across this question and tried to implement the suggested solution, but it's still not working for me. Apologies for any duplication. I have a simple link tag that is resulting in a 404 error: <Link className={classe ...

Leveraging an HTML interface in conjunction with a node.js application

My objective is to implement JavaScript on the server side. To achieve this, I have decided to use node.js as it seems like the most logical solution. While I am quite familiar with node.js from working on applications, I now need to utilize it for server- ...

The html-duration-picker is not being displayed in the proper format

I've been working on integrating an external library that allows for inputting document length. Specifically, I'm using the html-duration-picker library, but it seems like the input functionality is not quite right for durations. Could it be th ...