Substitute all attributes of objects with a different designation

I need to update all object properties from label to text.

Given:

[
  {
    "value": "45a8",
    "label": "45A8",
    "children": [
      {
        "value": "45a8.ba08",
        "label": "BA08",
        "children": [
          {
            "value": "45a8.ba08.45a8",
            "label": "45A8"
          }
        ],
        "checked": false
      }
    ]
  },
  ...
]

Needed:

[
  {
    "value": "45a8",
    "text": "45A8",
    "children": [
      {
        "value": "45a8.ba08",
        "text": "BA08",
        "children": [
          {
            "value": "45a8.ba08.45a8",
            "text": "45A8"
          }
        ],
        "checked": false
      }
    ]
  },
  ...
]

Answer №1

To begin, you can convert the data into a string using JSON.stringify(), then replace specific strings within the data. Finally, parse the modified string with JSON.parse():

var data = [
  {
    "value": "45a8",
    "label": "45A8",
    "children": [
      {
        "value": "45a8.ba08",
        "label": "BA08",
        "children": [
          {
            "value": "45a8.ba08.45a8",
            "label": "45A8"
          }
        ],
        "checked": false
      }
    ]
  }
];

data = JSON.parse(JSON.stringify(data).replaceAll('"label"', '"text"'));
console.log(data);

Additional Note: Another method to try is by utilizing Regular Expressions (RegEx) as shown below:

var data = [
  {
    "value": "45a8",
    "label": "45A8",
    "children": [
      {
        "value": "45a8.ba08",
        "label": "BA08",
        "children": [
          {
            "value": "45a8.ba08.45a8",
            "label": "45A8"
          }
        ],
        "checked": false
      }
    ]
  }
];
var find = '"label"';
var re = new RegExp(find, 'g');
data = JSON.parse(JSON.stringify(data).replace(re, '"text"'));
console.log(data);

Answer №2

If you want to simplify the data structure, you can iterate through the keys and locate the label key. Extract its value and assign it to a new key called text. Then remove the old key, which is label.

let data = [
      {
        "value": "45a8",
        "label": "45A8",
        "children": [
          {
            "value": "45a8.ba08",
            "label": "BA08",
            "children": [
              {
                "value": "45a8.ba08.45a8",
                "label": "45A8"
              }
            ],
            "checked": false
          }
        ]
      }
    ]
    
    for (const key in data.keys()){
      if(key === "label"){
        data.text = data[key]
        delete data.key
      }
    }

Answer №3

You can achieve the same using recursion. Here's an example:

const nestedArray = [ { "value": "45a8", "label": "45A8", "children": [ { "value": "45a8.ba08", "label": "BA08", "children": [ { "value": "45a8.ba08.45a8", "label": "45A8" } ], "checked": false } ] }];

changeLabelToText = arr => {
    return arr.map(({label, ...rest}) => {
      if(rest.children) rest.children = changeLabelToText(rest.children);
      return {text: label, ...rest}
    })
};

console.log(changeLabelToText(nestedArray));

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

I would greatly appreciate any recommendations on how to troubleshoot and

I've been working on the "Map the Debris" challenge at freecodecamp, and I'm facing an issue. While my code works fine in my PC's editor, it doesn't satisfy the conditions when I paste it into the website area. Any suggestions on how t ...

What is the best method for inserting a hyperlink into the JSON string obtained from a subreddit?

const allowedPosts = body.data.children.filter((post: { data: { over_18: any; }; }) => !post.data.over_18); if (!allowedPosts.length) return message.channel.send('It seems we are out of fresh memes!, Try again later.'); const randomInd ...

Display a division upon choosing an option

I am working on a project that involves a selection menu in the form of a drop-down list. <select> <option id="one" value="something">Car</option> <option id="two" value="anything">Plane</option> </select> Also, I ...

Is there a way to bring in both a variable and a type from a single file in Typescript?

I have some interfaces and an enum being exported in my implementation file. // types/user.ts export enum LoginStatus { Initial = 0, Authorized = 1, NotAuthorized = 2, } export interface UserState { name: string; loginStatus: LoginStatus; }; ex ...

The navigation menu dissolves into hiding at the uppermost part of the page upon scrolling upwards on iOS devices

I am currently working on creating a navigation menu that will automatically hide when scrolling down and reappear when scrolling up. This functionality works perfectly fine on desktop and Android browsers, but I have encountered an issue specifically with ...

Tips for positioning a div next to an input box when it is in focus

I am working on a scenario where I have used CSS to extend the search box when focused. The idea is that when the search box is focused, it should decrease in size and a cancel button should appear next to it. This is the CSS code I am using: .clrble .fr ...

How to successfully load the google-map-react library

After installing the google-map-react library locally in my app, I verified that it is listed in my package.json under dependencies. The corresponding folder also exists in the node_modules directory. However, when attempting to reference the component con ...

Manipulating Data in TypeScript: Creating a Mutated Copy of a List of Dictionaries

After going through multiple answers, it appears that there might be a logical error. However, I am struggling to find a solution for this issue. In TypeScript/JavaScript, I have two lists of dictionaries. One list is a copy of the other for tracking purp ...

How to ensure NodeJS waits for a response before returning a value

I've come across a seemingly simple problem that I just can't seem to solve. My current project involves working with an asynchronous messaging bot. In this particular scenario, the bot is supposed to react to an event by calling a Restful API a ...

Using AJAX to send an array as a response from Laravel

After implementing Laravel to handle an AJAX post request, I encountered an issue with displaying the route data. public function infoRoute(Request $request) { // Extracting required information $ship_id = $request->ship_id; ...

When attempting to add an item to an array within a sub-document using Mongoose and MongoDB, the error message "Property 'messages' not found" is returned

I am working with four different models: teacher, student, teacherMessageSchema, and studentMessageSchema. The teacherMessageSchema is a subdocument within the 'teacher' model under the messages: [teacherMessageSchema] property, while the student ...

Exploring ways to retrieve information stored in localStorage within an android mobile application

I am currently developing an Android App using phonegap. The app is a simple game that generates random numbers for math problems. If the user answers correctly, their score increases, but if they lose, their name and current score are saved in localStor ...

Utilizing the zIndex property on a map label does not produce any impact when combined with a GeoJSON layer

Utilizing the Google map label tool, I am trying to showcase certain property from GeoJSON data on a GeoJSON layer. However, the issue arises as the layer has a dark color and the label is appearing blurry behind the GeoJSON data layer. Despite attempting ...

I'm struggling to grasp the utilization of generics within the http.d.ts module in Node.js code

type RequestHandler< Request extends **typeof IncomingMessage = typeof IncomingMessage**, Response extends **typeof ServerResponse = typeof ServerResponse**, > = (req: InstanceType<Request>, res: InstanceType<Response> ...

Ways to dynamically emphasize text within ngFor loop

Within my ngFor loop, I have a set of rows. <div *ngFor="let block of data;"> <div class="class-row"> <div class="left">A Label:</div> <div class="right">{{block.key1}}</div> </div> <div class="clas ...

Insert an HTML element or Angular component dynamically when a specific function is called in an Angular application

Currently, I am working on a component that contains a button connected to a function in the .ts file. My goal is to have this function add an HTML element or make it visible when the button is clicked. Specifically, I would like a dynamic <div> elem ...

What is the best way to combine relative paths or create distinct identifiers for SVG files located within multiple layers of folders

I have a collection of icons exported from "Figma" organized in folders, and I'm using grunt-svgstore to create a sprite sheet. However, the result contains duplicated IDs even after trying 'allowDuplicateItems: false' and 'setUniqueIds ...

What are the best practices for utilizing ESM only npm packages alongside traditional npm packages within a single JavaScript file?

Hey there, I'm fairly new to web development and I encountered a problem when trying to require two packages, franc and langs, in my index.js file. It turns out that franc is now an ESM only package, requiring me to import it and mention type:module i ...

Could someone provide an explanation for the meaning of the phrase "class User extends Model<UserAttribute UserCreationAttribute>"?

View Image of the Issue I am puzzled by why we are utilizing both UserCreationAttribute and UserAttribute in that specific arrow, especially when UserCreationAttribute is created by omitting one field from UserAttribute. Can someone please clarify this fo ...

Always deemed non-assignable but still recognized as a universal type?

I'm curious about why the never type is allowed as input in generic's extended types. For example: type Pluralize<A extends string> = `${A}s` type Working = Pluralize<'language'> // 'languages' -> Works as e ...