Reputation: 8420
I have this function that sort some input object based on an array called keys
;
const keys = ["token", "agentID", "agentSequence", "allOptions"]
function sortRequest(request) {
return keys.reduce((sortedRequest, key) => {
if (key in request) {
sortedRequest[key] = request[key]
}
return sortedRequest
}, {})
}
console.log(sortRequest({
allOptions: false,
agentSequence: 6,
agentID: 123,
token: 'test',
notVisible: true
}));
The only problem is if some value of the input is not present on the array
it will be lost on the returned object. I'm trying to fix this issue, but couldn't get it. The idea is to get each property of the object.
Upvotes: 0
Views: 72
Reputation: 4837
Simple forEach
and spread
will do the trick.
const input = {
allOptions: false,
agentSequence: 6,
agentID: 123,
token: 'test',
notVisible: true
};
const keys = ["token", "agentID", "agentSequence", "allOptions"];
function orderInput(input, keys) {
let ordered = {};
keys.forEach(function (key) {
if (key in input) {
ordered[key] = input[key];
}
});
return {...ordered, ...input};
}
console.log(orderInput(input, keys));
Upvotes: 1
Reputation: 113866
Objects cannot be reordered. Objects are by definition unordered. Some javascript engine (most of them these days) do have some sort order but do not depend on it since the standard does not specify object key sorting behavior.
If you need a specific key order you need a Map. Or if you want to do it the traditional way you need an array:
[
["token", "agentID", "agentSequence", "allOptions"]
{ key: "token", value: 'test' },
{ key: "agentID", value: 123 },
{ key: "agentSequence", value: 6 },
{ key: "allOptions", value: false },
{ key: "notVisible", value: true}
]
This of course does not answer your question. Instead do not even attempt to do what you are doing.
Upvotes: 1
Reputation: 780724
After getting the properties that are in keys
, do a second pass over the original object and add in the properties that are missing.
const keys = ["token", "agentID", "agentSequence", "allOptions"]
function sortRequest(request) {
const result = keys.reduce((sortedRequest, key) => {
if (key in request) {
sortedRequest[key] = request[key]
}
return sortedRequest
}, {});
return Object.entries(request).reduce((sortedRequest, [key, value]) => {
if (!(key in keys)) {
sortedRequest[key] = value;
}
return sortedRequest;
}, result)
}
console.log(sortRequest({
allOptions: false,
agentSequence: 6,
agentID: 123,
token: 'test',
notVisible: true
}));
Upvotes: 1