I have an array of objects like this:
const customers = [
{
customer_name: 'Negan',
customer_age: 45,
customer_weapon: 'Bat',
customer_email: 'negan@sanctuary.com',
customer_city: 'Washington'
},
{
customer_name: 'Daryl',
customer_age: 41,
customer_weapon: 'Crossbow',
customer_email: 'daryl.dixon@kickass.com',
customer_city: 'Atlanta'
},
{
customer_name: 'Rick',
customer_age: 45,
customer_weapon: 'Magnum 357',
customer_email: 'rick@alexandria.com',
customer_city: 'King County'
},
]
and I want to replace all keys inside objects with these keys:
const newKeys = [
'firstname',
'age',
'weapon',
'email',
'city'
]
What is the best way to do this? An example will be appreciated!
To rename a key in an object:Use bracket notation to assign the value of the old key to the new key. Use the delete operator to delete the old key. The object will contain only the key with the new name.
To change the key name in an array of objects with JavaScript, we use the array map method. const arrayOfObj = [ { key1: "value1", key2: "value2", }, { key1: "value1", key2: "value2", }, ]; const newArrayOfObj = arrayOfObj. map(({ key1: stroke, ... rest }) => ({ stroke, ...
To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!
You can use Object.values()
to retrieve values and then array.reduce()
to compose a new object:
const customers = [
{
customer_name: 'Negan',
customer_age: 45,
customer_weapon: 'Bat',
customer_email: 'negan@sanctuary.com',
customer_city: 'Washington'
},
{
customer_name: 'Daryl',
customer_age: 41,
customer_weapon: 'Crossbow',
customer_email: 'daryl.dixon@kickass.com',
customer_city: 'Atlanta'
},
{
customer_name: 'Rick',
customer_age: 45,
customer_weapon: 'Magnum 357',
customer_email: 'rick@alexandria.com',
customer_city: 'King County'
},
];
const newKeys = [
'firstname',
'age',
'weapon',
'email',
'city'
];
let result = customers.map(obj =>
Object.values(obj).reduce((acc, cur, i) => {
acc[newKeys[i]] = cur;
return acc; }, {}));
console.log(result);
I strongly suggest the usage of a key replacement map over a simple list of new keys, for the latter is strongly depended on a customer object's key order.
If a customer object satisfies a 1:1 key mapping, go for an approach similar to this one, that maps a list of customer objects by creating a new customer object with each iteration step via reducing a list of key tuples with each tuple holding the old and the new key ...
function createNewCustomerFromOldOneViaBoundConfig(customer) {
return Object.entries(this).reduce((newCustomer, [key, newKey]) => {
newCustomer[newKey] = customer[key];
return newCustomer;
}, {});
};
const customerKeyReplacementMap = {
customer_name: 'firstname',
customer_age: 'age',
customer_weapon: 'weapon',
customer_email: 'email',
customer_city: 'city'
};
const customers = [{
customer_name: 'Negan',
customer_age: 45,
customer_weapon: 'Bat',
customer_email: 'negan@sanctuary.com',
customer_city: 'Washington'
}, {
customer_name: 'Daryl',
customer_age: 41,
customer_weapon: 'Crossbow',
customer_email: 'daryl.dixon@kickass.com',
customer_city: 'Atlanta'
}, {
customer_name: 'Rick',
customer_age: 45,
customer_weapon: 'Magnum 357',
customer_email: 'rick@alexandria.com',
customer_city: 'King County'
}].map(createNewCustomerFromOldOneViaBoundConfig, customerKeyReplacementMap);
console.log('customers : ', customers);
.as-console-wrapper { min-height: 100%!important; top: 0; }
As soon as at least one customer object violates a strict 1:1 mapping of its keys, one has to change the approach to creating and mutating a new customer object from its outdated counterpart.
This case also proves that any approach based on just a list of replacement keys is really limited to just a single kind of a customer object's key order (and structure) ...
function createNewCustomerFromOldOneAndMutateKeysViaBoundConfig(oldCustomer) {
return Object.entries(this).reduce((customer, [oldKey, key]) => {
customer[key] = customer[oldKey];
delete customer[oldKey];
return customer;
}, Object.assign({}, oldCustomer));
};
const customerKeyReplacementMap = {
customer_name: 'firstname',
customer_age: 'age',
customer_weapon: 'weapon',
customer_email: 'email',
customer_city: 'city'
};
const customers = [{
additional_key_1: 'FOO',
customer_name: 'Negan',
customer_age: 45,
additional_key_2: 'BAR',
customer_weapon: 'Bat',
customer_email: 'negan@sanctuary.com',
customer_city: 'Washington'
}, {
additional_key_1: 'BAZ',
customer_name: 'Daryl',
customer_age: 41,
additional_key_2: 'BIZ',
customer_weapon: 'Crossbow',
customer_email: 'daryl.dixon@kickass.com',
customer_city: 'Atlanta'
}, {
additional_key_1: 'FOOBAR',
customer_name: 'Rick',
customer_age: 45,
additional_key_2: 'BAZBIZ',
customer_weapon: 'Magnum 357',
customer_email: 'rick@alexandria.com',
customer_city: 'King County'
}].map(
createNewCustomerFromOldOneAndMutateKeysViaBoundConfig,
customerKeyReplacementMap
);
console.log('customers : ', customers);
.as-console-wrapper { min-height: 100%!important; top: 0; }
You can iterate over the objects, and then change the keys
of each property by the ones in newKeys
:
const customers = [
{
customer_name: 'Negan',
customer_age: 45,
customer_weapon: 'Bat',
customer_email: 'negan@sanctuary.com',
customer_city: 'Washington'
},
{
customer_name: 'Daryl',
customer_age: 41,
customer_weapon: 'Crossbow',
customer_email: 'daryl.dixon@kickass.com',
customer_city: 'Atlanta'
},
{
customer_name: 'Rick',
customer_age: 45,
customer_weapon: 'Magnum 357',
customer_email: 'rick@alexandria.com',
customer_city: 'King County'
},
]
const newKeys = [
'firstname',
'age',
'weapon',
'email',
'city'
]
for (let i = 0; i < customers.length; i++) {
let customer = customers[i];
let j = 0;
for(let p in customer){
customer[newKeys[j++]] = customer[p];
delete customer[p];
}
}
console.log(customers);
You can try using for...of
and for...in
loop:
const customers = [
{
customer_name: 'Negan',
customer_age: 45,
customer_weapon: 'Bat',
customer_email: 'negan@sanctuary.com',
customer_city: 'Washington'
},
{
customer_name: 'Daryl',
customer_age: 41,
customer_weapon: 'Crossbow',
customer_email: 'daryl.dixon@kickass.com',
customer_city: 'Atlanta'
},
{
customer_name: 'Rick',
customer_age: 45,
customer_weapon: 'Magnum 357',
customer_email: 'rick@alexandria.com',
customer_city: 'King County'
},
];
const newKeys = [
'firstname',
'age',
'weapon',
'email',
'city'
]
for(var o of customers){
var index = 0;
for(var k in o){
delete Object.assign(o, {[newKeys[index]]: o[k] })[k];
index++;
}
}
console.log(customers);
Map over the customers array and for each object in this array, iterate over its keys and add the values using these keys in a new object with the renamed property names. This way you will also avoid mutating original objects.
const customers = [
{ customer_name: 'Negan', customer_age: 45, customer_weapon: 'Bat', customer_email: 'negan@sanctuary.com', customer_city: 'Washington' },
{ customer_name: 'Daryl', customer_age: 41, customer_weapon: 'Crossbow', customer_email: 'daryl.dixon@kickass.com', customer_city: 'Atlanta' },
{ customer_name: 'Rick', customer_age: 45, customer_weapon: 'Magnum 357', customer_email: 'rick@alexandria.com', customer_city: 'King County' },
];
const newKeys = [ 'firstname', 'age', 'weapon', 'email', 'city' ];
const res = customers.map(obj => {
const newObj = {};
Object.keys(obj).forEach((k, i) => newObj[newKeys[i]] = obj[k]);
return newObj;
});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }
A better approach would be to make newKeys
an object that maps old keys to new keys. This way you won't have to rely on the ordering of keys in the objects.
For this, just change newKeys
to an object as shown below:
const newKeys = {
customer_name: 'firstname',
customer_age: 'age',
customer_weapon: 'weapon',
customer_email: 'email',
customer_city: 'city'
};
and change the code in the .map()
method in above code snippet to
const res = customers.map(obj => {
const newObj = {};
Object.keys(obj).forEach(k => newObj[newKeys[k]] = obj[k]);
return newObj;
});
You can do a simple map. This way the order of the keys doesn't matter.
const customers = [{
customer_name: 'Negan',
customer_age: 45,
customer_weapon: 'Bat',
customer_email: 'negan@sanctuary.com',
customer_city: 'Washington'
},
{
customer_name: 'Daryl',
customer_age: 41,
customer_weapon: 'Crossbow',
customer_email: 'daryl.dixon@kickass.com',
customer_city: 'Atlanta'
},
{
customer_name: 'Rick',
customer_age: 45,
customer_weapon: 'Magnum 357',
customer_email: 'rick@alexandria.com',
customer_city: 'King County'
},
]
var updated = customers.map(customer => {
const {
customer_name,
customer_age,
customer_weapon,
customer_email,
customer_city
} = customer;
return {
firstname: customer_name,
age: customer_age,
weapon: customer_weapon,
email: customer_email,
city: customer_city
}
});
console.log(updated);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With