Reputation: 2002
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:
How do I changed object's properties not only while iterating through them, but "forever"?:)
Appreciate any help:)
Upvotes: 0
Views: 1033
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
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
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