Prepending a string to the key of a JSON object using JavaScript

Is there a way to add 'd:' before the key of a JSON object?

Here is the JSON data:

"data": {
   "aa": "value",
   "ab": "value"
  }

The expected result should look like this:

"d:data": {
   "d:aa": "value",
   "d:ab": "value"
  }

Answer №1

Here is an example:

let obj = { "nested": {
   "one": "value",
   "two": "value"
  }
}

function addPrefixToKeys(object, prefix) {
    return Object.fromEntries(Object.entries(object).map(([key, value]) => {
        return [`${prefix}${key}`, typeof value === 'object' ? addPrefixToKeys(value, prefix) : value];
    }));
}

console.log(addPrefixToKeys(obj, 'n:'))

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

Strengthening JavaScript Security

Throughout the past few years, I have delved into various javascript libraries like Raphael.js and D3, experimenting with animations sourced from different corners of the internet for my own learning. I've obtained code snippets from Git repositories ...

The printing feature in javascript does not include the ability to print values from textboxes

I'm encountering an issue when trying to print an HTML table with textboxes that should get their values from another function. However, the preview is not showing anything. Below is the complete code: <html> <head></head> < ...

"Unable to get elements by tag name using the getElementsByTagName method in

function updateLayout() { var para = document.getElementsByTagName("p"); para[0].style.fontSize = 25; para[1].style.color = "red"; } <p>Text in paragraph 1</p> <p>Text in paragraph 2</p> <p>Text in paragraph 3</p& ...

Custom control unable to display MP3 file

Hey, I came across this awesome button that I am really interested in using: https://css-tricks.com/making-pure-css-playpause-button/ I'm currently facing two issues with it. First, I can't seem to play the sound. I've placed the mp3 file ...

Using Selenium to interact with drop-down lists using div tags instead of select tags

As a newcomer to automated testing using Selenium Web Driver, I am struggling to test drop down lists for the location type without relying on the select command. The element in question is enclosed within a div tag. I attempted sending keys but that meth ...

AngularJS $resource sends the id as a query parameter rather than including it in the URL

I'm trying to retrieve data from a rest API by using the product id as part of the URL, rather than as a query parameter. Here is the factory code: .factory('Products', ['$resource', function($resource) { return $reso ...

Injecting environment variables into webpack configuration

My goal is to set a BACKEND environment variable in order for our VueJS project to communicate with the API hosted there, but I keep receiving an error message saying Unexpected token :. Here is the current code snippet from our config/dev.env.js, and I&a ...

Collaborative Desktop & Web Application powered by Javascript REST/Ajax

Currently, my node.js back-end is seamlessly working with a web-based JavaScript client by sending AJAX requests. However, I am now contemplating creating a compact desktop version of the JavaScript client using solely JavaScript, specifically leveraging ...

What is the best way to incorporate multiple pages into a Node JS and Express application?

After completing a tutorial on Node JS for RPI (https://www.youtube.com/watch?v=QdHvS0D1zAI), I encountered an issue when trying to add multiple websites to my web app. While everything works fine locally on localhost:5000/page2, once I make the app public ...

Guide on activating javascript code for form validation using php

How can I activate JavaScript code for form validation? I am currently implementing form validation on a combined login/register form where the login form is initially displayed and the register form becomes visible when a user clicks a button, triggering ...

Acquire the content of an interactive website with Python without using the onclick event

I am looking to extract the content of a dynamically generated website after clicking on a specific link. The link is structured as follows: <a onclick="function(); return false" href="#">Link</a> This setup prevents me from directly accessin ...

The Json request is invalid because it contains the @ symbol

After validating the Json data online, it appeared to be correct. However, when I attempted to call the json array key, the editor showed a Parsing error: Unexpected character '@' The editor in question is Visual Studio Code, and it seems as tho ...

In Vue3, have you ever wondered why the $emit function seems to work fine before a promise fetch,

I have encountered an issue while attempting to pass the result of a promise fetch from a child component to a parent component using emit. Strangely, the emit function was working perfectly fine before the $fetch operation, allowing my parent component to ...

Using Django with Ajax without the need for the JQuery library

Exploring the world of Ajax without jQuery Library has been quite a journey. I recently created a basic view that displays a random number on the screen. After adding a button and invoking the ajax function, I encountered an issue where clicking the button ...

Unleashing a cascade of infinite promises

When it comes to handling an expensive computation within a function that is called frequently and needs to return quickly, my approach involves chaining promises together with this. This method seems to be effective in ensuring that computations occur seq ...

What is the best way to access a nested element within a JSON string using Scala?

Currently, I am utilizing Scala to parse JSON with a specific structure: { "root": { "metadata": { "name": "Farmer John", "hasTractor": false }, "plants": { "corn": 137.1 ...

Having issues with JavaScript function returning value from Ajax request

My AJAX request function is functioning well - returning 1 for success and 2 for failure. However, I am facing an issue when trying to perform actions outside of this function based on the return value. Instead of getting either 1 or 2, I always receive "u ...

Updating a MongoDB subarray with $set now includes adding a new entry rather than just updating existing ones

When trying to update an object in a sub-array, instead of replacing and updating the data, it adds a new entry. Here is the code from controller.js: const updateSubCategory = asyncHandler(async (req, res) => { const { dataArray } = req.body ...

Saving changes to mesh vertices in r67 of Three.js

I've encountered an issue with saving a mesh to a text file after manipulating vertices in my plane model. While the rendering on screen works as expected, the updates are not reflected in the saved file. Interestingly, if I move a vertex before the ...

Having trouble parsing the JSON response from the server using Android Gson

While the Json is technically valid, when attempting to parse it with Gson, an error occurs: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but encountered BEGIN_ARRAY at line 1 column 439 To view the enti ...