Sergej Fomin
Sergej Fomin

Reputation: 2002

Javascript changing object properties

I have an object and I am iterating through it's properties in order to change them (I want to replace 'a.1'-kind to 'a[1]'-kind):

.fail(function (data) {

var errors = data.responseJSON;
console.log("Object before: ", errors);


console.log("Changed properties:")
for (var property in errors) {
    if (errors.hasOwnProperty(property)) {



            if (property.includes('.')) {
                property = property.replace(/\./, "[");
                property = property.replace(/$/, "]");
                console.log(property);

            }

    }
}

console.log("Object after: ", errors);

The properties change during iteration, but object's properties don't change for real:

enter image description here

How do I changed object's properties not only while iterating through them, but "forever"?:)

Appreciate any help:)

Upvotes: 0

Views: 1033

Answers (3)

user5085788
user5085788

Reputation:

A functional approach:

function replaceProperties(obj) {

    var newObj = Object.getOwnPropertyNames(obj).reduce(function (newObj, prop) {

        var newProp = prop;

        if (prop.includes('.')) {
            newProp = prop.replace(/\./, "[").replace(/$/, "]");
        }

        newObj[newProp] = obj[prop];

        return newObj;

    }, {});

    return newObj;

}

var newObj = replaceProperties(errors);

Upvotes: 0

User 1058612
User 1058612

Reputation: 3819

Like the post from @Jonas w above, you can do a delete and reassign the value.

Another example here (does not include your string replacement/regex logic, but shows how you can update/alter the keys:

let logger = document.querySelector('pre');

let obj = {
  foo: 'foo-value',
  bar: 'foo-value',
  baz: 'foo-value',
  qux: 'foo-value'
};

logger.innerHTML = `Original: ${JSON.stringify(obj, null, 2)}\n`;

Object.keys(obj).forEach((oldKey) => {
  let newKey = oldKey + '-new';
  let originalVal = obj[oldKey];
  obj[newKey] = originalVal;
  delete obj[oldKey];
});

logger.innerHTML += `Updated: ${JSON.stringify(obj, null, 2)}\n`;
<pre></pre>

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138537

You may delete and reassign:

if (property.includes('.')) {
    errors[property.replace(/\./, "[").replace(/$/, "]")]=errors[property];
    delete errors[property];
}

You may ask why does

property=property.replace(..);

Not work? Well property is not related to object in any way. Its just a string...

Upvotes: 2

Related Questions