How do I make JS fetch function receive json/data from flask API in the same order as sent by flask?

54 views Asked by At

How do I make JS fetch receive json/data from flask API in the same order as sent by flask?

flask API:

@api_bp.route("/users")
def users():
    all_users = User.query.all()
    data = list([u.to_dict() for u in all_users])
    return data

print(data):

[{'id': 1, 'username': 'godo', 'email': '[email protected]', 'first_name': 'Godo', 'last_name': 'xxx'}]

JS script:

fetch( apiEndpoint + 'users' )
.then(response => response.json())
.then(data => {
  this.tableData = data;
})
.catch(error => {
  console.error('Error fetching data:', error);
});

data:

[{'email': '[email protected]', 'first_name': 'Godo', 'id': 1, 'last_name': 'xxx', 'username': 'godo'}]

The order of keys of the JSON when received by JS fetch is altered to a seemingly alphabetical or random order. I have read that there are technical explanations as to why this is the case, but I really need to receive the data in the same order. Reason: I will display this data using Bootstrap-vue in the browser, and the order is important.

1

There are 1 answers

0
dev On

The order of the keys in the JSON object is not guaranteed in JavaScript, so the order can be different from the order in which it was sent by Flask. However, you can use an array to specify the order of the keys and then map the data to a new object with the keys in the desired order.

fetch(apiEndpoint + 'users')
    .then(response => response.json())
    .then(data => {
        const orderedData = data.map(obj => {
            return keyOrder.reduce((acc, key) => {
                acc[key] = obj[key];
                return acc;
            }, {});
        });
        this.tableData = orderedData;
    })
    .catch(error => {
        console.error('Error fetching data:', error);
    });