Create a new JSON property by incorporating the value of an existing property

I have a file containing JSON-serialized data structured as shown below:

{
    "name":"Store",
    "children":[
        {
            "name":"Store 1",
            "children":[
                {
                    "name":"collection 1",
                    "description":"collection 1",
                    "children":[
                        {
                            "name":"Products",
                            "description":"Products",
                            "children":[
                                {
                                    "name":"Product 1",
                                    "description":"Product 1"
                                }
                            ]
                        }
                    ]
                }
            ],
            "description":"category 1"
        },
        {
            "name":"Store 2"
        }
    ]
}

My goal is to insert a title property for objects with a name, where the value of the title matches that of the name. Here is the desired structure after modification:

{
    "name":"Store",
    "title":"Store",
    "children":[
        {
            "name":"Store 1",
            "title":"Store 1",
            "children":[
                {
                    "name":"collection 1",
                    "title":"collection 1",
                    "description":"collection 1",
                    "children":[
                        {
                            "name":"Products",
                            "title":"Products",
                            "description":"Products",
                            "children":[
                                {
                                    "name":"Product 1",
                                    "title":"Product 1",
                                    "description":"Product 1"
                                }
                            ]
                        }
                    ]
                }
            ],
            "description":"category 1"
        },
        {
            "name":"Store 2",
            "title":"Store 2"
        }
    ]
}

Answer №1

To transform the Json data, we can utilize JSON.Parse for parsing and implement a recursive function to assign titles to all the descendants.

function TitleAssignment(items) {
  items["title"] = items["name"]
  if (items["children"] != undefined) {
    items["children"].forEach(element => {
      element = TitleAssignment(element)
    });
  }
  return items
}

var jsonText = '{"name":"Store","children":[{"name":"Store 1","children":[{"name":"collection 1","description":"collection 1","children":[{"name":"Products","description":"Products","children":[{"name":"Product 1","description":"Product 1"}]}]}],"description":"category 1"},{"name":"Store 2"}]}';
var itemData = JSON.parse(jsonText);
itemData = TitleAssignment(itemData);

Answer №2

const updateTitles = (data) => {
  data.title = data.name;
  if(data.children){
    data.children.forEach(updateTitles);
  }
}

const jsonData = {
  "name": "Fruit Market",
  "children": [{
      "name": "Apple Stand",
      "children": [{
        "name": "Gala Apples",
        "description": "Sweet and juicy Gala apples",
        "children": [{
          "name": "Red Delicious",
          "description": "Classic Red Delicious apple"
        }]
      }],
      "description": "Fresh fruit category"
    },
    {
      "name": "Vegetable Stand"
    }
  ]
};

updateTitles(jsonData);

console.log(jsonData);

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

Is it necessary to encapsulate Factory calls within a function in my Controller file?

Typically, I call a Factory from my Angular controller directly within the controller function without creating a separate method. For instance: (function () { 'use strict'; angular.module("Dashboard") .controller("DashboardController", D ...

What is the best method for returning the AJAX outcome to the JSP page?

Using AJAX, I am able to post data from my JSP page to my servlet. $.ajax({ url: 'myServlet?action=FEP', type: 'post', data: {machine: i, name: txt}, // where i and txt hold certain values success: f ...

Using an array of objects to set a background image in a Bootstrap carousel using jQuery: a step-by-step guide

I have an array of items, each containing a background property with a URL to an image. Here is my array: https://i.sstatic.net/jfrV0.png Here is the HTML structure: <div id="myCarousel" class="carousel slide" data-ride="carousel"> <ol ...

Changing the names of nested columns in R

I am interested in generating a json file that follows a specific schema: col1, col2, fields{name, value} Within my data frame, I have columns col1 to col4. My goal is to nest col3 and col4 under "field" and include the column name and its corresponding v ...

What is the best way to iterate through this using forEach?

let array = [{ query:{ q1 : 123, q2 : 44 } }]; Despite attempting to use a forEach loop, no results were returned. ...

What is the best way to ensure that a navbar dropdown appears above all other elements on

I'm having trouble creating a navbar dropdown with material design. The dropdown is working fine, but the issue I'm facing is that other elements are floating above it. https://i.stack.imgur.com/aJ0BH.png What I want is for the dropdown to floa ...

Cycle through JSON array utilizing an iterative loop

I've been struggling to properly iterate through a JSON array. The code I have attached is one of many variations that I have attempted, and it seems like I just can't wrap my head around it. Despite looking at multiple examples and reading up on ...

Previewing multiple images before uploading them using jQuery

Currently, I am utilizing the following code for my image uploader: HTML: <input type="file" id="files" name="files[]" multiple /> <ul id="list"></ul> JavaScript: function handleFileSelect(evt) { var files = evt.target.files; // FileL ...

Having difficulty running assessments on the connected components

I have encountered an issue while using the MERN stack and Redux. Specifically, I am facing errors when trying to write test cases for certain components. The error message I receive states: "Could not find "store" in the context of "C ...

optimal method of storing and retrieving an array in a database

I have a set of HTML inputs that can be regenerated using JavaScript to allow users to input their experience history. Let's assume this code is generated twice like the following: <!-- User Experience 1 --> <label>Company Name</label& ...

create a sapper route using JSON data

Beginning with the official Sapper template, I am keen on implementing export default as recommended by eslint: export default function get(_, res) { res.writeHead(200, { 'Content-Type': 'application/json', }); res.end(conte ...

Storing JSON data as a dictionary in Django's database

I am seeking guidance on how to properly save a field obtained from JSON as a dictionary in my database field. Currently, when attempting to do so, I encounter the error message: 'int' object is not callable Thank you in advance for your assi ...

Update each number in an array by appending a string within a table in an Angular component, rather than the

I have created a function that decides on a comment based on the result number added to an array and displays it in a table. However, calling this function within the template is causing a performance slowdown. Is there a way to achieve the same outcome w ...

View JSON data in a Power BI report

Displaying sample JSON data in my Power BI report is a key part of my documentation process. Many consumers frequently request sample JSON structure, so having this information readily available on the report streamlines my workflow. I initially attempted ...

Combine each module using grunt and then compress

Looking to achieve this using Grunt. My current file structure is as follows: /app --app.js --/module1 ----module1.js ----module1Model.js --/module2 ----module2.js ----module2Model.js How can I bundle and minify each module into a single file to appear ...

POST request with Vue Material formVue Material form submission using POST

I am working on creating a login page using vue-material. The base form I am using can be found here. My server side is built on laravel 5.4. This is my template: <div id="app"> <md-layout md-tag="form" novalidate @submit.stop.prevent="submit" ...

What is the best way to combine two arrays of characters or strings into a single array?

I have a question about creating an array to store a user's first and last names. The goal is to combine the two names separated by a comma and space in a third array using loops. While the task may seem simple, I've been struggling to get it ri ...

Collecting the standard output and standard error of a Node-API module executed within an Electron framework

During the development of my Node-API module alongside an Electron application, I encountered a dilemma. The N-API module runs within the render process of Electron due to its intricate API that would be challenging to navigate through a context bridge. Fu ...

Interactive drop-down menu for populating a input field

I have been searching everywhere for a solution to this issue but have not been able to figure it out. I was able to make it work when I needed a dynamic drop-down to adjust the values in a second drop-down and fill in a text value in a text box. Now, I w ...

Arranging Functions in JavaScript

I am encountering an issue regarding the execution of JavaScript functions within HTML. Specifically, I am using dimple.js to create a graph and need to select an svg element once the graph is created via JavaScript. Despite placing my jQuery selector as t ...