javascript - 在 Array Javascript 中的每个对象上运行函数
问题描述
我是 js 新手,希望得到一些帮助。
目前,我有一个函数,通过传递 obj 和 obj 键对的所需位置来重新排列对象内的键。
function orderKey(inputobject, keyplacement) {
keyplacement.forEach((k) => {
const v = inputobject[k]
delete inputobject[k]
inputobject[k] = v
})
}
要为单个对象运行此函数,我只需调用它并传递参数。
例子:
const value = {
foo: 1,
bar: 2,
food: 3
}
const desiredorder = ['foo', 'food', 'bar']
orderKey = (value , desiredorder)
console.log(value) // Will output => {foo:1 , food: 3 , bar:2}
假设输入是这样的:
const value = [{
foo: 1,
bar: 2,
food: 3
},
{
foo: 2,
bar: 3,
food: 4
},
]
如何将函数 orderKey 分配给数组中的每个对象,以获得每个对象的所需位置?
最有效的循环是什么?
非常感谢任何帮助。
谢谢。
解决方案
我会像这样使用地图功能。
//please add the return statement
function orderKey(inputobject, keyplacement) {
keyplacement.forEach((k) => {
const v = inputobject[k]
delete inputobject[k]
inputobject[k] = v
})
return inputobject;
}
const value = [{
foo: 1,
bar: 2,
food: 3
},
{
foo: 2,
bar: 3,
food: 4
}]
const desiredOrder = ['foo', 'food', 'bar']
// suggestion using map function.
// creates a new array populated with all the resulting objects.
let newValues = value.map(actualValue => {
return orderKey(actualValue, desiredOrder);
})
console.log(newValues)
推荐阅读
- kubernetes - K3S 集群在 Rancher 仪表板中待处理
- python - 执行帖子后关闭浏览器选项卡
- python - 如何放大 matplotlib 图并单击以向缩放窗口添加一个点?
- jenkins - Jenkins管道阶段 - 循环目标目录的子目录
- bootstrap-4 - 弹出窗口在 spring-webflow 和 jsf2.2 中不起作用
- d3.js - 是否可以将叶节点放置在另一个下方而不是彼此相邻?
- date - 我如何使上一年的财政年度达到最大值?
- c++ - Cout 引号似乎不起作用(C++)
- php - Laravel 8:在空的多对多关系中使用枢轴时出错
- java - 强制 runOnUiThread