I have an object:
var obj = {
'a|a' : 1,
'b|b' : 2
}
I wanted to change the obj
to something like:
var obj = {
'aa' : 1,
'bb' : 2
}
where the attribute a|a
was changed to aa
.
Is there a way to do the same ?
I have an object:
var obj = {
'a|a' : 1,
'b|b' : 2
}
I wanted to change the obj
to something like:
var obj = {
'aa' : 1,
'bb' : 2
}
where the attribute a|a
was changed to aa
.
Is there a way to do the same ?
You can do it like this:
Object.getOwnPropertyNames(obj).forEach(function (key) {
obj[key.replace('|', '')] = obj[key];
delete obj[key];
});
Simply iterate through all object keys and assign values to new key (without |
characted), and delete the old key afterwards.
var obj = {
'a|a': 1,
'b|b': 2
}
let keys = Object.keys(obj);
let newObj = {};
for (let key of keys) {
let transformedKey = key.replace("|","") ; // transform your key
newObj[transformedKey] = obj[key]
}
console.log(newObj);
This is fix your usecase.
There are a number of ways to iterate over an Object. I think the most straightforward method is using a for..in
statement:
for (let key in obj) {
console.log(key, '=>', obj[key]);
}
So changing the key name would involve using String.replace
to change the key name:
var obj = {
'a|a' : 1,
'b|b' : 2
}
let newObj = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key.replace('|', '')] = obj[key];
}
}
console.log(newObj);
If you don't want to create a new object, you could add the new key and delete obj[key]
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
obj[key.replace('|', '')] = obj[key];
delete obj[key];
}
}
Another method would be to use Array.reduce
over the keys/properties:
Object.getOwnPropertyNames(obj).reduce((p, c) => {
p[c.replace('|', '')] = obj[c];
return p;
}, {});