2

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.

1

2 Answers 2

2

You can use a forEach loop on value

value.forEach(val => orderKey(val, desiredOrder))
Sign up to request clarification or add additional context in comments.

1 Comment

Works nicely as well.
1

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

1 Comment

Thank you, this is a great solution. Thanks for the reference as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.