What is the best way to dynamically update object keys?

Long explanation ahead, please bear with me. I'm ready to share all the necessary code to solve the problem, but I'm a bit lost on where to start. First, let me explain the issue at hand, and I would greatly appreciate any help from someone who can assist.

In my application using Vue/Vuex, an interesting (at least to me) problem has emerged: I have an Array filled with Objects of documents retrieved from a MySQL DB. Each time a user selects one of these documents from a list, it gets moved from the documents Array to the "Selected" Object of Objects. It is then given a unique key, which is the current route where the user is located. The structure looks something like this:

/machines/1/home : { }

Later on, if the user opens another tab, selects another document, etc., the "Selected" now appears as follows:

{/machines/1/home : { }, /machines/2/home : { }, /machines/3/home : { }}

Once all this is done, for each tab (identified by its current route), a distinct document is displayed. However, when the user closes the last tab, the document along with its key are successfully removed. But if they decide to close the second out of three tabs, everything falls apart because we end up with tabs 1 & 3 remaining in "Selected," while the routes of the tabs are still:

{/machines/1/home, /machines/2/home}

Therefore, what I'm wondering is: Is there a way to update the object keys still present in "Selected" to match the new tabs?

Answer №1

Utilizing an Array of Objects for the 'selected' variable allows for the creation of an Object of Objects when necessary.

When an item is deleted from an Array, such as the 2nd item, the subsequent items will shift up to fill the empty space.

For example:

const selectedArray = [{
  val: 'one'
}, {
  val: 'two'
}, {
  val: 'three'
}];

// remove/close 2nd tab
let removedTab = 2;
selectedArray.splice(removedTab - 1, 1);

const selected = selectedArray.reduce((a, d, i) => {
  a[`/machines/${i + 1}/home`] = d;
  return a;
}, {});

console.log(selected)

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

Create dynamic automatic titles in HTML with JavaScript

Below is the code snippet to add an image with a link to the home-page and an h1 with the document name (if there isn't one already). This HTML code includes a JavaScript file reference in the <head> section and uses a <h1> tag for the ti ...

Trouble encountered with JSX in my custom React Library after transitioning to Preact

I've created a straightforward React library that I implement with my own state management, utilizing just a Higher Order Component: import React from 'react'; const connect = (state, chunk) => Comp => props =>{ const newProps ...

Creating Uniform Heights Across Devices with Responsive Design Strategies

I am struggling with a height consistency issue that I cannot figure out. The problem can be seen in this Fiddle: FIDDLE Here is the code snippet: $(document).ready(function() { if ($(window).width() > 768) { $(window).ready(function() { ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

The onCreated listener function in the jBox Modal dialog is experiencing issues and not functioning properly after the first use

I am using jBox from the URL: . Every time I click on a link, a modal is created. The first time the modal is created, listeners for the buttons on that modal are properly added in the "onCreated" attribute and work when clicked. However, from the second ...

What is the best way to retrieve all information from GitLab API using Axios?

I am looking to retrieve data from all the projects stored on my GitLab server. As I understand, GitLab usually displays a default of 20 projects per page, so I need to adjust the setting to show more projects at once: https://gitlab-repo.com/api/v4/proje ...

Enhancing arrow cone spin with ThreeJs

My arrow function is supposed to connect pick and place points using QuadraticBezierCurve3 and ConeGeometry, but the rotation of the cone doesn't align perfectly with the curve as shown in the snippet below! I'm seeking advice on how I can enhan ...

The Node.contains() function in JavaScript does not verify the presence of inner child elements

I have developed a custom DatePicker component for my React app and I am facing an issue with hiding it on outside click, similar to how I handled other components like Select Dropdown. To address this problem, I created a custom hook: export default (ref, ...

Execute a separate function when clicking on certain buttons without interfering with the buttons' original onclick function (which has already been assigned) - JavaScript

While I am still relatively new to JavaScript and learning, I have developed a webpage with multiple buttons that trigger different functions on click events. However, I would like to additionally call another function when any of these buttons are clicked ...

Steps to resolve the error message 'npm ERR! Cannot read property 'startsWith' of null':

As I embark on creating my very first react-native app, I encountered a stumbling block while trying to set up the react-native command line interface following the instructions provided here. Every attempt I make to initialize the react-native command lin ...

Combining the redux toolkit function createAsyncThunk with Angular's HttpClient by leveraging the ApiService

Currently, I am working on incorporating @reduxjs/toolkit into an Angular project. Is there a way to pass an Angular service as a parameter to the callback of createAsyncThunk instead of utilizing fetch directly? I referenced the documentation for an exa ...

Using loops to simulate the effects of :hover in Javascript for each child div element, as an

For a while now, I've been utilizing the code below (or something similar) to showcase information on specific posts: Html: <div class="main"> <div class="info"> <div>Words</div> <div>Words</div> < ...

What is the best way to handle multiple axios calls with pagination in a React application?

Discussing React Pagination and Handling Multiple Axios Calls In my current project, I am faced with the challenge of mapping through an array of numbers and making sequential API calls for each one. The API I'm working with returns paginated results ...

What is the most effective method for creating unit testing functions in JavaScript?

When it comes to JavaScript, there are multiple ways to write the same functions. For example, consider the following options. Which approach is ideal for unit testing scenarios? // Option 1 ============ var app = {}; app.name = "abc" app.init = funct ...

Get the ability to overlay text onto an image by using jQuery for downloading

Currently, I am facing an issue with an online photo editor in my project. The problem is that I am unable to download the image after adding and editing text on it. The texts added are editable but the image cannot be downloaded after the changes. I nee ...

The jQuery execCommand feature fails to generate a pop-up when used within the contenteditable attribute of an HTML tag

Trying to implement an inline text editor using the jQuery execCommand function. Below is a snippet of my source code: /*******************************************************************/ /********** Click: inner of contenteditable text-editor div *** ...

Troubleshooting issue with Vue3 - TS Custom State Management

Issue: I am facing a challenge in transferring data between two separate components - the main component and another component. Despite attempting to implement reactive State Management based on Vue documentation, the object's value remains unchanged ...

Learn how to efficiently pass multiple props using a loop in Vue

I am dealing with an object that has multiple properties. Typically, I know which props I want to pass to my component and do it like this: <component :prop1="object.prop1" :prop2="object.prop2" :prop3="object.prop3" /> However, I want to pass the ...

Discover the power of manipulating arrays in AngularJS using angular filters

Let's say I have two Angular filters: translate, which manipulates strings in some way, and sort, which sorts strings alphabetically. I want to display strings from an array str sorted based on their translation. Here is the code I want to make work: ...

Error in VueJS/Typescript: Module 'my-module' or its type declarations are not found

Hey fellow developers! I'm currently working on a Vue2 setup with Nuxt and Typescript. I'm facing an issue while trying to install the awesome vue-slick-carousel module via yarn. When attempting to import the module in my component, Typescript th ...