Implement a new list field to an object using javascript

I am facing a challenge in converting a JSON object to a list of JSON objects and then adding it back to JSON. Here is an example:

config = {
  existing_value: 'sample'
}


addToListing = (field, value, index=0) => {
  config = {
    ...config,
    listing: {   
      ...config.listing,
      [field]: value
    }   
  }
}

addToListing('first', 1, 0)
addToListing('second', 2, 0)
addToListing('first', 3, 1)


console.log(config)

Result:

{
  existing_value: 'sample', 
  listing: 
  { 
    first: 3, 
    second: 2 
  } 
}

Desired outcome:

{ 
  existing_variable: 'example', 
  listing: 
  [
    {first: 1, second: 2}, 
    {first: 3}
  ] 
}

I have attempted various methods but I couldn't achieve the expected result (like using nested values or initializing at the beginning).

Can anyone provide assistance?

Answer №1

To enhance the functionality, consider implementing additional checks and resetting the array.

const addToListing = (field, value, index=0) => {
    config = {
        ...config,
        listing: Object.assign(
            [],
            (config.listing || []), 
            { [index]: { ...(config.listing?.[index] || []), [field]: value } }
        )    
    }
};

var config = { existing_variable: 'example' };

addToListing('first', 1, 0);
addToListing('second', 2, 0);
addToListing('first', 3, 1);

console.log(config)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Eliminate the use of the optional chaining operator ?. by introducing more default values.

const addToListing = (field, value, index=0) => {
    config = {
        ...config,
        listing: Object.assign(
            [],
            (config.listing || []), 
            { [index]: { ...((config.listing || [])[index] || []), [field]: value } }
        )    
    }
};

var config = { existing_variable: 'example' };

addToListing('first', 1, 0);
addToListing('second', 2, 0);
addToListing('first', 3, 1);

console.log(config)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Here is a different approach I suggest using the Array.prototype.splice() method.

let data = {
  current_value: 'sample'
}


const addToDataList = (property, val, idx = 0) => {
// Check if dataList property does not exist then initialize it with an empty array
data.dataList || (data.dataList = [])

data.dataList.splice(idx, 1, (data.dataList[idx] ? {...data.dataList[idx], [property]: val} : {[property]: val}));
}

addToDataList('itemA', 1, 0)
addToDataList('itemB', 2, 0)
addToDataList('itemA', 3, 1)


console.log(data);
.as-console-wrapper {min-height: 100% !important; top: 0;}

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

The messaging feature is not functioning properly within the page tab

The iframe page tab is not compatible with the Send dialog. I followed the example on the 'Send Dialog' page https://developers.facebook.com/docs/reference/dialogs/send/ <html xmlns:fb="https://www.facebook.com/2008/fbml"> <body> ...

Eliminate any undefined data in the popup map of Javascript

I am working with JSON data that is being displayed in a pop-up on a map. In cases where there is missing data (Visibility), the word undefined appears in the pop-up. Is there a way to remove the undefined text so that it does not show up in the pop-up? ...

Leveraging JSON Data in Highcharts

I am looking to create a column range chart using Highcharts to display a series of high and low temperatures. I found a demo example that showcases the kind of chart I want on the Highcharts website at: The data I have is stored in a file named datatest. ...

The event SelectedIndexChanged is not triggering as expected on dropdown lists that are created dynamically

My Telerik RadComboBox triggers Javascript on change to fetch data from the database via AJAX and populate a second dropdown list. I need to fill text boxes based on the selection of the second dropdownlist. The code for the two dropdownlists is as follows ...

Juggling various perspectives in a Backbone assortment

As I develop a Backbone application that includes a section for viewing reports, there are three key components: a menu of report links, the title of the displayed report, and the content of the displayed report. Users are expected to click on a report lin ...

The ID Token could not be verified due to an invalid jwt.split function

I'm currently working on validating a Google ID Token on my Node.js server. Unfortunately, I've encountered the following error: The ID Token cannot be verified: jwt.split is not a function For reference, here is the link to the code that I am ...

Creating divs that adapt to different screen sizes without relying on flexbox

Currently, I am in the process of developing a chat interface where the viewport height is set to 100vh. The layout consists of a header/navbar, a "main content" section, and a footer housing the input field (you can view the code here) The way I have str ...

Import information from a SqlServer Database into a jQuery Full Calendar utilizing the capabilities of Codeigniter3

I've been dealing with this issue for quite some time now. I used to work with the same calendar in PHP, but since my project is in Codeigniter, it's not fitting properly. Therefore, I have switched to working with Codeigniter. Controller Code ...

Troubleshooting unexpected issues with dynamically updating HTML using innerHTML

Need help with a renderWorkoutUpdated function that replaces specific workout records with updated values. _renderWorkoutUpdated(currentWorkout) { let html = `<li class="workout workout--${currentWorkout.type}" data-id="${ curre ...

Is it possible to implement an automatic clicking function on a bootstrap navigation bar similar to a carousel?

I am working on a website with a bootstrap navigation bar similar to the one shown in this image : bootstrap nav <ul class="nav nav-tabs" id="tab_home" role="tablist"> <li class="nav-item" role="pres ...

Using Selenium Webdrivers to Browse Pages with Minimal Resource Loading

I'm attempting to restrict Javascript from altering the source code of the site while testing with Selenium. Disabling Javascript completely in the Webdriver is not an option as I require it for testing purposes. Below is my approach for the Firefox W ...

Updating GridView row only if there are changes, the value remains unchanged in JavaScript. Disappointing

Incorporating a gridview (ASP.net) inside an update panel, I included a "Save" button that triggers a loop through all the rows of the grid view to pass data to a stored procedure for updating each row. However, this process proved to be slow and resulted ...

Tips for distinguishing between submit() and other JavaScript functions, and understanding why submit() may not be functioning as expected

In the table, I have a list of users with "update" and "delete" links added at the end of each line. To enable this functionality, I implemented a JavaScript function that captures the user ID, sets another field to "true," and inserts these values into a ...

Standardize JSON by mapping classes and arrays to individual columns

I am in need of help converting a JSON structure into a tabular format. The JSON input looks like this: { "039.png" : [ "finding1" ], "006.png" : [ "finding1", "finding2" ], "012 ...

Trouble arises when attempting to append a class through ng-class upon clicking

In a specific scenario, I am trying to change the border color from black to red in a div by appending a class using ng-class when clicked. However, when clicking a button, the modal opens but the class is not being appended as expected. <div ng-class ...

Elements found in array but not present in the table

Seems like I'll have to revise my question once more - those downvotes are quite frustrating... I've got an array of IDs and a table to cross-reference them with. Here's the query I'm currently using: SELECT COUNT(*) FROM orders WHERE ...

Organizing information in local storage using an array and converting it to a string

After storing user inputs (Worker's name, Car Vin, Start time and End time) in the local storage, you want to sort the employees' names in alphabetical order. The question is where should the code be placed and how should it be written? // Car C ...

When transitioning from another page, the header will cover a portion of the section

I am facing a specific issue that I need help with. My goal is to have the navigation bar link to different sections of a single page when clicked. For example, clicking on "Contact" should take the user to the contact section, and then if they click on "A ...

What is the best way to assign string values from an array in data() to the src attribute of an image element?

I've been working on a feature where the <div.box> element appears based on the user's input through a form. In this project, I'm using vue3 and v-for to iterate over an array 'images' that contains URL strings linking to ima ...

What are some ways to slow down the speed of my animation?

Currently, I am creating a HTML5 game where I have implemented javascript to make my character move in response to the user pressing the arrow keys. The movement animation consists of 6 sprites. However, I have encountered an issue where when I hold down ...