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.
Object.getOwnPropertyNames() instead of Object.keys() to ignore enumerability...Object.keys() was perfectly valid. This was just a suggestion, you did not have to edit your code. ;)getOwnPropertyNames is better in this case :]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; }, {}); key is going to look like "a|a", so key.replace('|', '') will yield 'aa'. The value of obj['a|a'] (or obj[key]) is 1, so this would look like obj['aa'] = obj['a|a'] or obj['aa'] = 1obj[c]'s value to it; however, it is not due to the immutability of strings, but the immutability of object properties names, which is why we have to delete the old key.