首页 > 解决方案 > 在 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 分配给数组中的每个对象,以获得每个对象的所需位置?

最有效的循环是什么?

非常感谢任何帮助。

谢谢。

标签: javascriptfor-loopobjectkey

解决方案


我会像这样使用地图功能。

//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)

这是参考Array.prototype.map()


推荐阅读