Adjusting an item according to a specified pathway

I am currently working on dynamically modifying an object based on a given path, but I am encountering some difficulties in the process. I have managed to create a method that retrieves values at a specified path, and now I need to update values at that path. The length of the path should not be a limiting factor, so using prop.prop.prop.prop should still work. For instance:

let dataObj = {
  name: 'Old Name',
  address: {
    state: 'CA',
    timezone: 'America/California'
  }
}

let modifiedValues = {
  'name': 'New Name'
  'address.state': 'FL',
  'address.timezone': 'America/New_York'
}

My goal is to iterate over the second object and utilize the key-value pairs to either update the first object directly or construct a new object with the same structure. Ultimately, I aim to achieve an object as follows:

let dataObj = {
  name: 'New Name',
  address: {
    state: 'FL',
    timezone: 'America/New_York'
  }
}

Additionally, below is the method I currently have for retrieving a value based on a provided path:

getAttributeFromPath(path: string, entity: any): any {
  return path.split('.').reduce((a, b) => a && a[b], entity);
}

Answer â„–1

If you want to modify the first object by setting an attribute from a path, you can create a customized version of getAttributeFromPath.

I have demonstrated this with a function called setAttributeFromPath, using forEach instead of reduce:

let dataObj = {
  name: 'Old Name',
  address: {
    state: 'CA',
    timezone: 'America/California'
  }
};

let modifiedValues = {
  'name': 'New Name',
  'address.state': 'FL',
  'address.timezone': 'America/New_York'
};

const setAttributeFromPath = (path, entity, value) => {
  const pathParts = path.split('.');
  let obj = entity;
  
  pathParts.forEach((part, index) => {
    if (obj[part]) {
      if (index < pathParts.length - 1) {
        obj = obj[part];
      } else {
        obj[part] = value;
      }
    }
  });
};

Object.entries(modifiedValues).forEach(([key, value]) => {
  setAttributeFromPath(key, dataObj, value);
});

console.log(dataObj);

You may wish to try crafting a more concise one-liner form of setAttributeFromPath using reduce.

Answer â„–2

For this task, you can utilize the eval function. All you have to do is loop through your modified values and update them accordingly.

let originalData = {
  title: 'Old Title',
  info: {
    category: 'Tech',
    rating: '5 stars'
  }
}

let updatedValues = {
  'title': 'New Title',
  'info.category': 'Business',
  'info.rating': '4 stars'
}

function modifyObject(values, object){
    Object.keys(values).forEach( property => {
        eval(`object.${property} = values[property]`);
    });
}

modifyObject(updatedValues, originalData);
console.log(originalData);

Answer â„–3

To efficiently organize your data, iterate through each item and check for any values that have a dotted structure. Then, construct a new object with the updated layout:

let revisedValues = {
    'name': 'Brand New Name',
    'address.state': 'California',
    'address.timezone': 'America/Los_Angeles'
};

let formattedValues = {};
for(let entry in revisedValues){
    if(entry.includes('.')){
        let separated = entry.split('.');
        if(separated[0] in formattedValues)
            formattedValues[separated[0]][separated[1]] = revisedValues[entry];
        else{
            formattedValues[separated[0]] = {};
            formattedValues[separated[0]][separated[1]] = revisedValues[entry];
        }
    }else{
        formattedValues[entry] = revisedValues[entry];
    }
}
console.log(formattedValues);

Answer â„–4

Check out this optimized and streamlined approach to a function that involves assigning values by using the last value as reference:

let dataObj = {
  name: 'Old Name',
  address: {
    state: 'CA',
    timezone: 'America/California'
  }
}

let modifiedValues = {
  'name': 'New Name',
  'address.state': 'FL',
  'address.timezone': 'America/New_York'
}

function setAttributeFromPath(path, entity, value) {
  const final = (path = path.split('.')).pop();
  path.reduce((a, b) => a && a[b], entity)[final] = value;
}

for(const key in modifiedValues) setAttributeFromPath(key, dataObj, modifiedValues[key]);

console.log(dataObj);

The loop operation can be integrated into the function itself utilizing array destructuring in the following manner:

function setAttributesFromPath(pathMap, entity) {
  Object.entries(pathMap).forEach(([path,value]) => {
    const final = (path = path.split('.')).pop();
    path.reduce((a, b) => a && a[b], entity)[final] = value;
  });
}

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

Express/NodeJS encountering a CORS problem, causing services to be inaccessible in Internet Explorer

Currently, I am working on a REST-based service implemented in Express/NodeJS. The code includes CORS (Cross Origin Resource Sharing) implementation to allow services to be consumed from browsers like Chrome and Firefox. However, there seems to be an issue ...

Locate the index of each distinct element within the array

Let's define an array called 'arr' with some elements: [7, 9, 30, 40, 50, 8, 1, 2, 3, 40, 90,2, 88,1] We also have another output array defined as: [0, 1, 2, 3, 4, 5, 6, 7, 8 ,10, 12] I stored this code snippet on a javascript ...

Is there a way to embed HTML code within a JavaScript variable?

Embedding HTML code within Java Flow can be quite interesting For instance: Check out this JSFiddle link And here's how you can incorporate it into your script: widget.value += ""; Generating a Pro Roseic Facebook POP-UP Box through Widg ...

Navigate to a local server running on localhost:3000 and access the external URL www.google.com

When attempting to access an external URL, the website that should open in a new tab is redirecting to http://localhost:3001/www.google.com instead of www.google.com. <IconButton key={index} size="large" color="primary" href={e.url ...

How come .trim() isn't cooperating with me?

I am encountering an issue with this particular piece of javascript. Every time I attempt to use it, nothing is displayed in my div. Instead, it simply adds ?weight=NumberInputed&measure=lbsOrkgs&submit=Submit to the URL. <h2>What size d ...

Having trouble retrieving data from JSON using JavaScript

Hey folks, I need some help with the following code snippet: function retrieveClientIP() { $.getJSON("http://192.168.127.2/getipclient.php?callback=?", function(json) { eval(json.ip); });} This function is used to fetch the IP address of visitors. When i ...

Every time I attempt to execute mupx deploy, an error message appears

issue in console shubhabrata@shubhabrata-VirtualBox:~/Meteor/myapp$ mupx deploy Meteor Up: Advancing Meteor Deployments for Production Configuration file : mup.json Settings file : settings.json “ Discover Kadira! A powerful tool to monitor yo ...

Getting data from a PHP request using AngularJS can be achieved by creating an HTTP request in

I am trying to send a basic REST service request using Angular for the PHP code below. Unfortunately, the request is resulting in an error. Check out the live code here PHP Code <?php /* Simple array */ $json = array("status" => 0, "msg" => ...

A step-by-step guide on changing an image

Is it possible to change an image when the user clicks on a link to expand its content? <ul class="accor"> <li> Item 1 <img src="../plus.png"> <p> Lorem ipsum dolor sit amet</p> </li> </ul> $(' ...

ng-options do not refresh automatically when modifying elements in the array

Having trouble updating the data in a select list? It seems that when selecting 'test', the value retrieved from the API is 'ÅšlÄ…sk' even though it's not listed. For example: I select 'test' but it shows as 'ÅšlÄ ...

Identifying the HTML elements beneath the mouse pointer

Does anyone know the method to retrieve the HTML tag located directly under the mouse cursor on a webpage? I am currently developing a new WYSIWYG editor and would like to incorporate genuine drag and drop functionalities (rather than the common insert at ...

Access specific data from a jQuery event

How can I retrieve the value of a custom attribute called itemID in order to include it in the URL just like I do with id? Here is the JavaScript code: <script type="text/javascript"> $(document).ready(function(){ $('.eventImage').cl ...

What is the best way to generate a "JSON diff" that can be displayed in the JavaScript console?

When working on my Angular project, I frequently encounter the need to compare JSONs in my Karma/Jasmine tests. It would be incredibly useful to have a console output showing what has been added and removed when comparing two structures. For example, ident ...

Finding all parent IDs from a given child ID within a nested JSON structure that contains children can be achieved by recursively

function loadKendoTreeView() { if ($("#treeview").data("kendoTreeView") != null) { $("#treeview").data("kendoTreeView").destroy(); $("#treeview").empty(); } var jsonData = [{ "Id": "239297d8-5993-42c0-a6ca-38dac2d8bf9f", ...

In Angular, the process of duplicating an array by value within a foreach function is not

I have been attempting to duplicate an array within another array and make modifications as needed. this.question?.labels.forEach((element) => { element["options"] = [...this.question?.options]; // I've tried json.stringify() as wel ...

Issue: Trouble with ajax form functionality

I'm a beginner in ajax, js, and php. Recently, I set up a simple contact form. <form id="contact-form" method="post" action="process.php" role="form"> <div class="messages"></div> <div class="form-group"> <l ...

Mastering the syntax of Babel in Node.js

Hey there! I've encountered a syntax issue while migrating to babel. The problem lies in importing an unnamed module. In traditional Node.js default import, it's possible to import without specifying the module name and passing in the app. Howeve ...

Calculating every number within a range of dates and storing them in the format of [day, hour]

Given two date pairs represented as numbers [hour, weekday], where hour ranges from 0-23 and weekday ranges from 1-7. I am tasked with generating all the hours in between each pair. For example, if given [13, 2] and [2, 3], the output would be: [13,2] [14 ...

Having trouble with Angular routing when attempting to directly access a specific URL path?

Seeking help with my routing setup in Angular. Using v12 of Angular. Encountering a 404 Not Found error when trying to access the direct URL for "register" at somesite.com/register. Uncertain if this is a server or Angular issue. Here is my router module ...

Customizing Material UI: Grouping Tab components within a div container

How can I wrap the children of a Material UI Tabs component in divs? <Tabs value={value} indicatorColor="primary" textColor="primary" onChange={handleChange} > <div> <Tab label="x" /> ...