What's the simplest method for updating a single value within a nested JSON object using TypeScript?

Using TypeScript version ^3.5.3

Consider the following JSON data:

const config = {
  id: 1,
  title: "A good day",
  body: "Very detailed stories"
  publishedAt: "2021-01-20 12:21:12"
}

To update the title using spread syntax:

const newConfig = {
  ...config,
  title: "A new day"
}

The updated newConfig object will be:

{
  id: 1,
  title: "A new day",
  body: "Very detailed stories"
  publishedAt: "2021-01-20 12:21:12"
}

In a different scenario, we have:

const config = {
  id: 1,
  articleConfig: {
    version: "2",
    configs: [
      {
        title: "A good day",
        body: "Very detailed stories"
        publishedAt: "2021-01-20 12:21:12"
      }
    ]
  }
}

An attempt to change the title value like this:

const newConfig = {
  ...config,
  articleConfig: {
    configs: [
      {
        title: "A new day"
      }
    ]
  }
}

Results in breaking the defined JSON schema:

const newConfig: {
    id: number;
    articleConfig: {
        version: string;
        configs: {
            title: string;
            body: string;
            publishedAt: string;
        }[];
    };
}

Is there a simple way to overwrite just one item in such type of JSON structure?

Answer №1

let previousConfig = { /* ... */ };

let updatedConfig = {
  ...previousConfig,
  articleSettings: {
    ...previousConfig.articleSettings,
    configurations: config.configurations.map(setting => ({
       ...setting,
       heading: "A fresh start"
    }))
};

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

Transforming varied JavaScript objects into a serial form

In my application, there is a concept of an interface along with multiple objects that implement this interface in various ways. These objects are created using different factory methods, with the potential for more factories to be added as the application ...

Unused function in Vue error compilation

I am facing an issue with the compiler indicating that the function 'show' is defined but never used. The function show is being used in HTML like this: <b-card> <div id="draw-image-test"> <canvas id="can ...

Using Typescript to automatically infer strongly-typed recursive index types

Commencing with an Animal interface and a detailed map of animals residing on my farm: export interface Animal { species: string; edible: boolean; } export interface FarmMap{ [key: string]: Animal; } Everything seems to be running smoothly. Here ...

Troubleshooting permission problems with Yarn and node_modules in a Docker environment

I have a Docker container containing a Symfony 6 web application and various other services like php-fpm, node, and python. Additionally, I have separate containers for MySQL and Nginx, all running on Alpine 3.15. My current issue arises when I execute do ...

Enhance the original array of a recursive treeview in VueJS

After going through this tutorial, I decided to create my own tree view using recursive components in Vue.js. The structure of the input array is as follows: let tree = { label: 'root', nodes: [ { label: 'item1', nod ...

Adding a fresh element to an array in Angular 4 using an observable

I am currently working on a page that showcases a list of locations, with the ability to click on each location and display the corresponding assets. Here is how I have structured the template: <li *ngFor="let location of locations" (click)="se ...

The Vue.js application which utilizes Vue I18n encountered the error message: "Unable to define i18n due to TypeError"

I am currently working on implementing internationalization in my Vue.js project using Vue I18n. Although I've been following the documentation found at , I encountered the following error message: [Vue warn]: Error in render: "TypeError: i18n is un ...

How can I expand and collapse elements using Angular?

I'm looking to implement a collapsible feature. When the user clicks on the "Section Title", I want the corresponding information to collapse or expand. @Component({ selector: 'knowledge-base', template: ` <div *ngFor="let sect ...

Placing information within a nested array with multiple levels of nesting

I'll try to keep this concise, Here is the structure of the schema... import mongoose from 'mongoose' const QuestionSchema = mongoose.Schema({ questionTitle: { type: String, required: " title"}, questionBody: { type: Stri ...

An easy way to place text along the border of an input field in a React JS application using CSS

I am struggling to figure out how to create an input box with text on the border like the one shown in the image below using CSS. I have searched extensively but have not been able to find any solutions to achieve this effect. I attempted using <input&g ...

Issue: The keyword in React/React-Native is returning a boolean value instead of the expected element object

I've recently delved into learning and coding with React, and I'm encountering a bug that I need help fixing. The issue lies within my application screen where I have two checkboxes that should function like radio buttons. This means that when on ...

Executing numerous Ajax requests within a single Rails view

Two ajax requests are being used on a single page, one showcasing a date and the other displaying a calendar. The first request updates the date upon clicking a date on the calendar. The second request allows for switching between months on the calendar. ...

Is there a way for me to retrieve the current value of a star rating when I click on it?

Looking for assistance with a ReactJS rating stars component that behaves oddly. The starting value is set to 5 stars, but each click on the stars seems to return the previous value rather than the current one. import React, {useState} from "react&quo ...

Focus issue with MUI Custom Text Field when state changes

Currently, I've integrated the MUI library into my React Js application. In this project, I'm utilizing the controlled Text Field component to establish a basic search user interface. However, an unexpected issue has surfaced. Following a chang ...

Utilize an external JavaScript file function within an AngularJS controller

I have an external JavaScript file with additional functions that I am trying to call from an Angular controller. Here is an example of the external.js file: ... ... function fun() { ... ... } ... ... The controller in question is called acccountCon ...

When trying to access an array within a nested reactive form group, a linting error was encountered

I'm currently working on a method to delete rows from a dynamic form, but I am struggling to target the array. The structure of my form group is as follows: this.piForm = this.fb.group({ milestoneSaveModel: this.fb.group({ milestonesToCr ...

How can I exclude attributes ending with Specified that are generated by xsd when serializing and deserializing in C# with the help of json.net?

I developed a C# Application. One of the classes in my application was generated from an xsd file using xsd.exe. Here is how the class looks: public class Transaction { public bool amountSpecified {get; set;} public double amount {get; set;} } ...

Accept a JSON-sending POST request in a JSP file via JavaScript

I have developed an HTML page with an input field. Using javascript, I extract the input value, convert it into JSON format, and attempt to send it through ajax. Additionally, I have a JSP application where a Java method processes this JSON data to store i ...

Take away the attention from the span element

I have been experimenting with the following jsfiddle and attempted various methods suggested in this Stack Overflow thread, but I am struggling to remove the focus from the "feedback" span after clicking on the cancel button in jQuery confirm dialog. Her ...

Using Underscore.js to Group JSON Data in jQuery

I am looking to format my JSON data in order to create a chart for my daily reporting templates. The chart should display the number of Approved, Rejected, and Pending items on a daily basis. The current JSON data I have is as follows: json_data = '[ ...