Tips on utilizing path variables within JSON paths

I'm attempting to utilize a path variable within a JSON path.

The issue I'm facing is that my variable is being added as a new key to the JSON object instead of replacing the path.

Here's an Example of My Code

Data = {
    first:{
        "Name":"John",
        "Age":"43"
    }
}

let path = "first.name"
let value = "Jan"

Data[path] = value
console.log(Data)

Current Result

Data = {
    first:{
        "Name":"John",
        "Age":"43"
    },
    "first.name": "Jan",
}

Desired Outcome

Data = {
    first:{
        "Name":"Jan",
        "Age":"43"
    }  
}

Any suggestions on how to resolve this issue? Appreciate your assistance 🙏

Answer №1

If you're searching for a solution to manipulate an object based on a given path, this script might be just what you need. All it needs is the correct path to work its magic! :-)

function updateObjectAttribute(obj, path, value){
    let objCopy = obj;
    let attributeNames = path.split('.');
    for(let index = 0; index < attributeNames.length-1; index++){
        objCopy = objCopy[attributeNames[index]];
    }
    objCopy[attributeNames[attributeNames.length-1]] = value;
    return obj;
}


Data = {
    first:{
        "Name":"John",
        "Age":"43"
    }
}

updateObjectAttribute(Data, "first.Name", "Jan");
console.log(Data);

This script efficiently modifies object attributes by taking advantage of the shared reference between objCopy and obj.

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

What is the best way to transfer data from a parent component to a child component in ReactJs?

When dealing with nested react elements, how can you pass values from the parent element to a child element that is not directly inside the parent element? React.render( <MainLayout> <IndexDashboard /> </MainLayout>, document.b ...

What is the best way to utilize eslint in Vue components?

I'm facing an issue with my .vue file that defines a component. Other .vue files are unable to see it properly due to linter errors. I keep getting ES Lint errors like: Cannot find module '../components/LinkButton'. I have tried several st ...

Parallel Execution Issue with RxJS Observable forkJoin

Struggling to understand why my requests aren't executing concurrently with the following code. As a newcomer to RxJS and observables, I would greatly appreciate any guidance on improving this snippet below. Essentially, I am fetching data from a REST ...

The data submitted from the form did not successfully get inserted into the database row

Currently, I am working on integrating a new product into my products database using ajax with php and mysql PDO. The form is located in a separate HTML file and gets loaded into a Bootstrap modal when the "add product" button is clicked. Below you can fi ...

The asynchronous function is not being executed by onSubmit

I am attempting to create a function that will generate a gif when the "get gif" button is pressed. However, I am facing an issue where nothing shows up in the console and the page reloads. 1) The requirement is for the client to enter a value 2) Set th ...

Locate MongoDB documentation pertaining to arrays of objects with two specific fields

For instance, consider a Mongo db collection: [ { "user_id": 1, "lead_id": 901, ... ... }, { "user_id": 2, "lead_id": 902, ... ... }, { "user_id": 2, & ...

Error: The data entered is invalid because the delimiter ":" [0x3a] is missing in nodejs

I seem to be encountering an issue: Error: The data is invalid and there seems to be a missing delimiter ":" [0x3a] at Function.decode.find (/Users/Seleena/Documents/torrent/node_modules/bencode/lib/decode.js:114:9) at Function.decode.buffer ...

Switch out 2 Bootstrap columns for 2 concealed columns with just a click. Utilizing Rails 4 and Bootstrap

Using Twitter Bootstrap 3 for a column system showcasing four similar advertisements at the bottom of the page. Code Snippet: <div class="row similar"> <% @recomended_ads.each do |advertisement| %> <div class="col- ...

Is there a way to eliminate an object from a multidimensional nested array in JavaScript and retrieve the parent array?

Can anyone help me figure out how to delete the "fields" object with id 47 from this nested array using JavaScript and return the entire parent array? [{ "id": 10, "name": "phone", "fields": [ { ...

Placing a hyperlink within template strings

Currently, I am working on implementing a stylish email template for when a user registers with their email. To achieve this, I am utilizing Express and Node Mailer. Initially, my code appeared as follows: "Hello, " + user.username + ",&bs ...

Utilize middleware nesting in Express.js

I am interested in implementing middleware to validate requests based on a RAML file. Below is an outline of my current code: // dependencies let resources = require('osprey-resources'); let errorHandler = require('request-error-handler&apo ...

Learn how to seamlessly transfer a JSON Document into a Cloudant NoSQL Database

Struggling to import a json file into my Cloudant database. Despite my limited knowledge on the topic, this seemingly simple task has proven to be quite challenging. I came across a video tutorial Importing JSON documents into a NoSQL DB in Bluemix using ...

What Causes the Response to Vary in a Post Request?

Issue: When I use console.log(res.data), it shows different data compared to console.log(JSON.parse(res.request.response)). My Next.js application is sending a post request to an internal API. The response from the REST endpoint should contain a list obje ...

Regular expression for precise numerical values of a specific magnitude (any programming language)

I have been searching for a solution to what I thought was a common problem but haven't found one yet. What I need is a regular expression that will fail on a specific number of significant figures (a Max), but pass for fewer than the Max. It should ...

Unable to establish connection with nodejs server from external devices

Currently, I am leveraging a React client along with a Node.js server (MERN Stack). The server operates smoothly on my computer; however, I encounter difficulties when attempting to connect from my mobile phone to the IPv4 of my PC using the correct port ...

What is the best way to retrieve the session identifier when utilizing Socket.IO?

I am in need of managing unique connections for my chat application. After doing some research, I realized that all the solutions I came across are outdated. Therefore, I am wondering how I can retrieve a socket's session ID using Socket.IO. The tec ...

How can I troubleshoot the issue of not being able to display elements in my list in

I am struggling with an issue regarding my patient list. I am trying to create a JTree from my JSON list by converting it into a regular list. However, I am unable to display the name of each patient. Please review my code below and provide any suggestions ...

Learning how to read JSON data in vb.net is crucial for effective

I have successfully obtained a JSON string as the result text from the code snippet below. resp = webRequest.GetResponse Dim status = resp.StatusCode If (status = 200) Then respStream = New StreamReader(resp.GetResponseStream(), encoding) resultText ...

react-video-recorder` facing challenges with loading

I recently integrated react-video-recorder into my application. After checking out the demos on Stackblitz and Storybook hosted on Vercel, I was impressed with how well it worked in my browsers. However, when I added it to my codebase, the component would ...

Using JavaScript, extract the most recent 10 minutes worth of UNIX timestamps from a lengthy array

I am working with an array that contains multiple UNIX timestamps and I need to retrieve the timestamps from the last 10 minutes. Specifically, I only require the count of these timestamps, possibly for a Bot protection system. Would it be best to use ...