Goal: to create an object with an specific order defined by an object, but only when the fields exists on the input data.
What I have and done:
This object defines the order:
const fieldsOrder = {
  token: undefined,
  agentID: undefined,
  agentSequence: undefined,
  allOptions: undefined
}
This is the body request that I need to sort:
const request = {
  allOptions: false,
  agentSequence: 6,
  agentID: 123,
  token: 'test'
}
The sorted object is sortedObject
const sortedObject = Object.assign(fieldsOrder, request);
console.log(sortedObject);
{
  agentID: 123,
  agentSequence: 6,
  allOptions: false,
  token: 'test'
}
Not working.
I was trying what I found here: Changing the order of the Object keys....
Here are some tests:
// This object defines de order:
const fieldsOrder = {
  token: undefined,
  agentID: undefined,
  agentSequence: undefined,
  allOptions: undefined
}
// 1st case: all fields
// This is the body request that I need to sort:
const request = {
  allOptions: true,
  agentSequence: 6,
  agentID: 123,
  token: 'test',
}
// The sorted object is `sortedRequest`
const sortedRequest = Object.assign(fieldsOrder, request);
// WRONG order...
console.log(sortedRequest); 
/*
I expected this order:
{
  token: 'test'
    agentID: 123,
  agentSequence: 6,
  allOptions: false
}
*/
/*************************************/
// 2nd case: some fields
const requestShort = {
  allOptions: true,
  agentID: 123,
  token: 'test',
}
const sortedRequest2 = Object.assign(fieldsOrder, requestShort);
// WRONG order...
console.log(sortedRequest2); 
/*
I expected this order:
{
  token: 'test'
    agentID: 123,
  allOptions: false
}
*/How could I fix it? I need to order the request by fieldsOrder but only using the fields on the requestobject.
 
     
     
     
     
    