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

Leveraging a single Axios request across various components

My current setup involves making a simple Axios call in this way: .get('https://myAPI.com/') .then(response => { this.info = response.data }) Subsequently, I utilize a v-for array loop on my components to display the retrieved data. ...

What methods can be used to accurately display the data type with TypeOf()?

When working with the following code: const data = Observable.from([{name: 'Alice', age: 25}, {name: 'Bob', age: 35}]); console.log(typeof(data)); The type is displayed as Object(). Is there a way to obtain more specific information? ...

I'm having trouble getting rid of this stubborn loader on the website

I am currently utilizing the following template: . My objective is to eliminate the preloader progress bar that displays the loading progress of the page in percentage. The files associated with this preloader are as follows: Loader CSS File - www[dot]the ...

The switch statement within Angular returns null when using getElementById()

In my single page application, I am using ng-switch to switch between different 'pages'. One of these pages contains a modal that is opened using the following function: var modal = document.getElementById('myModal'); vm.openModal = fu ...

Malfunction detected in Json autocomplete function

Currently, I am working on implementing an auto-complete search feature using data from my database. The PHP code below creates an array for this purpose: $leaders= mysql_query("SELECT model_name,model_id FROM models ORDER by model_name D ...

conceal elements using the <option> class隐藏

Although it seems like a simple task, I'm struggling to make it work. I created a form where the user can select a month from a list using the tags: <select> <option> When the selection is changed, the class .gone from the day SELECT is ...

Troubleshooting: Issue with jQuery not retrieving the value of input:nth-child(n)

My goal is to dynamically change the price when the model number changes, requiring the id number and quantity to calculate it accurately. Here is the HTML code I have: <div class="col-sm-9 topnav"> <span> ...

Eliminate nested object properties using an attribute in JavaScript

I am working with a nested object structured like this const data = [ { id: '1', description: 'desc 1', data : [ { id: '5', description: 'desc', number :1 }, { id: '4', description: 'descip& ...

The previous successful execution of req.body is now yielding an undefined value

My req.body is suddenly undefined, even though it was working fine a few days ago. I've tried using the deprecated body-parser module, but no luck. Here's my code: JS: var express = require("express"); var router = express(); require(& ...

Creating chained fetch API calls with dependencies in Next.js

I am a novice who is delving into the world of API calls. My goal is to utilize a bible api to retrieve all books, followed by making another call to the same api with a specific book number in order to fetch all chapters for that particular book. After ...

What kind of registration does React Hook Form use?

When utilizing react-hook-form alongside Typescript, there is a component that passes along various props, including register. The confusion arises when defining the type of register within an interface: export interface MyProps { title: string; ... ...

Running a Redux Thunk action from within a TypeScript environment, beyond the confines of a React component

Currently, I am in the process of converting a React Native app into TypeScript. Unfortunately, I have encountered an issue with dispatching thunk actions outside of the store. Below is how my store is configured: store/index.ts import { createStore, app ...

When attempting to use the .split method, an error is thrown stating that addEventListener is not

I'm attempting to create a table that automatically fills in the next input when I select options from MySQL. However, when I run this code, I get an error saying "addEventListener is not a function." I'm not very familiar with JavaScript, so I&a ...

Having trouble troubleshooting C++ code in Visual Studio Code

Recently, I downloaded Visual Studio Code v1.7.1 to work on my c++ coding assignments for my degree program. While my programming skills are at a basic level, I am quite impressed with VS Code, except for one thing - I have no clue how to debug or build my ...

Adjust picture dimensions when the window changes (using jQuery)

Hey there, I'm in need of some help resizing images on my webpage. I want the images to adjust their size when the page loads or when the browser is resized. The images can be either portrait or landscape, and they will be contained within a div that ...

Manipulating JSON data by replacing values with other JSON data in Python

When working with a nested JSON object, the goal is to modify values and add a new JSON Object. Consider the following JSON Object: { "key1": "value1", "key2": { "key2_1": "value2_2 ", ...

The error message being displayed states that 'null' cannot be used as an object when evaluating 'response.productType'

Hey everyone, I'm fairly new to working with Ajax and I've encountered an error in my code that says: TypeError: 'null' is not an object (evaluating 'response.productType'). I'm not sure why this is happening. Below is th ...

Angular Directives in Error

Help needed with creating a custom directive in Angular. Seeking guidance :) I am trying to display the content from 'directive.html' within the 'app-info' directive. The code functions properly without the directive, indicating a mist ...

Associate text with a color from a predetermined list (JavaScript)

As I work on adding tags to my website for blog posts, I have a specific vision in mind. Each tag should be assigned a unique background color selected from a predefined array of theme colors. My goal is to assign the same background color to tags with id ...

TypeScript Error: The Object prototype must be an Object or null, it cannot be undefined

Just recently, I delved into TypeScript and attempted to convert a JavaScript code to TypeScript while incorporating more object-oriented features. However, I encountered an issue when trying to execute it with cmd using the ns-node command. private usern ...