Here is what my object looks like:
let myObj = {
"Accounts": [
{
"Type": "Card",
"CreditCard": {}
},
{
"Type": "ACH",
"CreditCard": {}
},
{
"Type": "CDA",
"Checking": {}
},
{
"Type": "INTL",
"Mortgage": {}
}
]
}
I’d like to change the property name from CreditCard,Checking,Mortgage
to something common such as FinanceRecord
. I know I can do something like below
let temp = myObj.map(({ CreditCard: FinanceRecord, ...item }) => ({
FinanceRecord,
...item,
}));
// Specify each property name...
myObj.map(({ Checking: FinanceRecord, ...item }) => ({
FinanceRecord,
...item,
}));
Is there any better way to do this? I have about 20 different property names which I want to update. Thanks!
Edit:
Expected Output:
let myObj = {
"Accounts": [
{
"Type": "Card",
"FinanceRecord": {}
},
{
"Type": "ACH",
"FinanceRecord": {}
},
{
"Type": "CDA",
"FinanceRecord": {}
},
{
"Type": "INTL",
"FinanceRecord": {}
}
]
}
4
Answers
Yes, there is a more concise way to achieve this using the
Object.entries()
andArray.map()
methods. Here’s how you can update all the properties named CreditCard, Checking, and Mortgage to FinanceRecord:In the above code,
Object.entries(account)
returns an array of key-value pairs for each property of the current account object. We then loop through each key-value pair using afor...of
loop, and check if the key is one of the property names we want to update. If it is, we update the key to "FinanceRecord" in theupdatedRecord
object. If it’s not, we leave the key as is. Finally, we return theupdatedRecord
object for each account using theArray.map()
method.If the
Type
of the item specifies what the other property name will be, then you can use a map to do "dynamic destructuring"a way to do this UPDATE
test
You can do this without any destructuring (and therefore without making whole new objects) by adding the desired new property name and then deleting the old one:
Then:
Now in the interest of full disclosure, deleting properties probably blows away per-object internal optimizations that the runtime has done before that point. Well, maybe it does.