Is there a way to change the key names in an array of object?
Code:
List of value to change the key name.
var keys = {
id:'identifier',
facility:'site',
status:'info',
date:'days'
};
Array of object to change the key names
var arrayObj = [{
id:'jr210',
facility:'earth',
status:'sample info',
date:'Feb 29, 2020'
},
{
id:'tl980',
facility:'mars',
status:'sample info',
date:'Jan 15, 2020'
}]
Expected output:
var newArrayObj = [{
identifier:'jr210',
site:'earth',
info:'sample info',
days:'Feb 29, 2020'
},
{
identifier:'tl980',
site:'mars',
info:'sample info',
days:'Jan 15, 2020'
}]
You can use
reduce
andObject.entries
for the operation.reduce
is to re-group the property in the objectObject.entries
is to retrieve the key and value pairs in the object.This is a
map
ping task. Like almost every array methodmap
allows a 2nd argument, thethisArg
, a context which is bound to the callback method’s apply/call time.The provided approach implements a callback method
remapObjectWithBoundKeys
which utilizes its this context as configuration of how to remap each of an object’s key. It does so byreduce
ing theentries
of its key-config and creating a new object by iterativelyassign
ing new key-value pairs to it.