0

I have an object with simple key value pairs and an array with just key names. I would like to sort the objects keys by the order of the keys in the array.

A simplified example:

const obj = {
"bread": 11,
"butter": 6,
"milk": 40,
}

const orderedKeys = ["milk", "butter", "bread"]

const expectedResult = {
"milk": 40,
"butter": 6,
"bread": 11,
}

In this example I know the amount of keys in both the array and the object, however in reality I don't know the amount and in reality the object can also have more keys than specified in the array. In this case I just want the unknown keys at the end of the object.

What would be the cleanest way to solve this problem?

2 Answers 2

2

You can take advantage of Array.prototype.reduce which allow to perform different manipulation on array and return another kind of object or array

const obj = {
"bread": 11,
"butter": 6,
"milk": 40,
}

const orderedKeys = ["milk", "butter", "bread"]

const expectedResult = orderedKeys.reduce((accumulator, current) => {
   return {...accumulator, [current]: obj[current]};

}, {})

console.log(expectedResult);

If you want to add key which aren't present in the orderedKey but are present inside of the obj you can perform it like this

const obj = {
    "bread": 11,
    "butter": 6,
    "milk": 40,
    "cheese": 5
}

const orderedKeys = ["milk", "butter", "bread"]

let expectedResult = orderedKeys.reduce((accumulator, current) => {
    return {...accumulator, [current]: obj[current]};
}, {});

expectedResult = Object.assign({}, expectedResult, obj);
console.log(expectedResult);

Sign up to request clarification or add additional context in comments.

Comments

1

The simplest way is probably this:

  1. map the ordered keys to [key, value] tuples
  2. Reconstruct the object from those using Object.fromEntries
  3. ...spread the remaining object properties

const obj = {
    unknown: 15,
    bread: 11,
    butter: 6,
    milk: 40,
}

const orderedKeys = ['milk', 'butter', 'bread']

const orderedObj = {
    ...Object.fromEntries(orderedKeys.map(k => [k, obj[k]])),
    ...obj,
}

console.log(orderedObj)

However, relying on the order of keys in an object is generally a bad idea, because JavaScript objects are typically considered to be unordered ({ a: 1, b: 2 } is usually considered equivalent to { b: 2, a: 1 }). Whether or not they're ordered in practice depends somewhat on implementation. For this reason, and depending on your use case, you could consider using a Map instead:

new Map(orderedObj)

Comments

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.