javascript - 如何重命名对象数组中对象的所有键?
问题描述
有没有办法更改对象数组中的键名?
代码: 更改键名的值列表。
var keys = {
id:'identifier',
facility:'site',
status:'info',
date:'days'
};
更改键名的对象数组
var arrayObj = [{
id:'jr210',
facility:'earth',
status:'sample info',
date:'Feb 29, 2020'
},
{
id:'tl980',
facility:'mars',
status:'sample info',
date:'Jan 15, 2020'
}]
预期输出:
var newArrayObj = [{
identifier:'jr210',
site:'earth',
info:'sample info',
days:'Feb 29, 2020'
},
{
identifier:'tl980',
site:'mars',
info:'sample info',
days:'Jan 15, 2020'
}]
解决方案
This is a map
ping task. Like almost every array method map
allows a 2nd argument, the thisArg
, a context which gets bound to the callback method and thus is accessibly at such a 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 by reduce
ing the entries
of its key-config and creating a new object by iteratively assign
ing new key-value pairs to it.
const sampleList = [{
id:'jr210',
facility:'earth',
status:'sample info',
date:'Feb 29, 2020',
}, {
id:'tl980',
facility:'mars',
status:'sample info',
date:'Jan 15, 2020',
}];
function remapObjectWithBoundKeys(item) {
const keyConfig = this;
return Object
.entries(keyConfig)
.reduce((obj, [recentKey, currentKey]) => Object.assign(obj, {
[currentKey]: item[recentKey]
}), {});
}
console.log(
sampleList.map(remapObjectWithBoundKeys, {
id: 'identifier',
facility: 'site',
status: 'info',
date: 'days',
})
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
The advantage of the implemented method is that it operates independently from a map
task. One easily can utilize or re-use it for any kind of object (re)creation ...
function remapObjectWithBoundKeys(item) {
const keyConfig = this;
return Object
.entries(keyConfig)
.reduce((obj, [recentKey, currentKey]) => Object.assign(obj, {
[currentKey]: item[recentKey]
}), {});
}
const planetType = {
id:'tl980',
facility:'mars',
status:'sample info',
date:'Jan 15, 2020',
};
const recreatePlanetItem = remapObjectWithBoundKeys.bind({
id: 'identifier',
facility: 'site',
status: 'info',
date: 'days',
});
console.log(
planetType,
recreatePlanetItem(planetType)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
推荐阅读
- node.js - 错误:无法读取 undefined_NodeJS 的属性“名称”
- python - 如何理解 PyMC 模型中“产量”的使用?
- mongodb - 查询期间文档的MongoDB求和字段
- java - 我应该为我的所有方法编写空检查吗?
- python - 如何使用代码单元格中的行号将 Jupyter Notebook 导出为 html
- buffer - s-lang 中的 jed:总是在所有缓冲区中换行
- kubernetes - kubectl 端口转发到另一个端点
- react-native - PanGestureHandler 在 React Native 中的 setState 后立即取消
- php - 如何更改 Apache 中的绝对路径?
- node.js - 如何使用 Node 在 vscode 中调试电报机器人