SachiDangalla SachiDangalla - 1 year ago 113
Javascript Question

How to replace a dynamically specified attribute in JS object

The attribute(or the nested object) is selected dynamically based on conditions. It can be one of the 4 possibilities as follows:

var tempData = o.title ? o["properties"] || o["items"]["properties"] : o[k]["properties"] || o[k]["items"]["properties"];

Then I get this new data, I want to replace the above selected with.

var newData = //some new Object

I want to replace whatever above selected with the new data. I could do the following (go through the condition again and set the new data):

if (o["properties"]) {
o["properties"] = newData;
} else if (o["items"]["properties"]) {
o["items"]["properties"] = newData;
if (o[k]["properties"]) {
o[k]["properties"] = newData;
} else if (o[k]["items"]["properties"]) {
o[k]["items"]["properties"] = newData;

But it doesn't look good. What is the more sophisticated way of achieving this?

Answer Source

It is unclear if you are generically attempting to replace any properties property with the newData, or if you are wanting it to specifically be one of the ones you have specified in your code. I have assumed that you are only wanting to replace the ones you specifically have shown in your code.

As a first pass, I would do something like:

var p;
if (o.title) {
} else {
if ( { = newData;
} else if ( { = newData;

If you are going to perform the replacements in other areas of your code, or if you are going to use property names other than hard coded items, and properties, then you should create a function. Assuming you are only performing this replacement in this section of your code, using a variable to hold the object in which you are looking for properties is faster/more efficient than creating a function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download