Reputation: 69
I'm new to js, and would like some help.
Currently, I have a function, that re-arranges keys inside an object, by passing the obj and the desired position of the obj key pairs.
function orderKey(inputobject, keyplacement) {
keyplacement.forEach((k) => {
const v = inputobject[k]
delete inputobject[k]
inputobject[k] = v
})
}
To run this function for an individual object, I simply call it and pass the parameters.
Example:
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}
Suppose the input is like this:
const value = [{
foo: 1,
bar: 2,
food: 3
},
{
foo: 2,
bar: 3,
food: 4
},
]
How can I assign function orderKey to each object in the array, to get the desired position for each object?
What is the most efficient loop for this?
Any help is highly appreciated.
Thanks.
Upvotes: 2
Views: 1397
Reputation: 781068
You can use a forEach
loop on value
value.forEach(val => orderKey(val, desiredOrder))
Upvotes: 2
Reputation: 124
I would use the map function like this.
//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)
Here is the reference Array.prototype.map()
Upvotes: 1