How to sort an object with Javascript?

Asked

Viewed 142 times

-2

I’m creating a function that takes elements from a . json file and creates options for a select in HTML dynamically. This file is ordered, but when it is presented in HTML it is disordered.

Example . json

{
  "01": {
    "regiao": "Dubai",
    "name": "Dubai",
    "address": "Jebel Ali Free Zone South JAFZA Job 19, Office 1301, P.O. box 261901 – Dubai – UAE (Unitade Arab Emirates)",
    "phone": "+971 4 885-5404",
    "fax": "+971 4 885-5405",
    "email": "[email protected]",
    "time": "9:00 às 18:00 (GMT +4)"
  },
  "02": {
    "regiao": "Jerusalém",
    "name": "Jerusalém",
    "address": "3rd Floor, Gati Tower, Kiryat Hamada 3, Har Hotzvim, Jerusalem, P.O Box 45316",
    "phone": "+9720732495829",
    "fax": "",
    "email": "[email protected]",
    "time": "9:00 às 18:00 (GMT + 2)"
  },
  "03": {
    "regiao": "Centro Oeste BR",
    "name": "Brasília – DF",
    "address": "Endereço: SAUN Quadra 05, Bloco C, Torre II, salas 1201 a 1701 – Centro Empresarial CNC – CEP: 70.040-250 – Brasília-DF",
    "phone": "+55 61 2027-0202",
    "fax": "",
    "email": "[email protected]",
    "time": "9:00 às 18:30"
  }
}

Example of code to create elements:

fetch(URL)
  .then(function(resp) {
    if (resp.status !== 200) {
      console.warn('Error: ' + resp.status);
      return;
    }

    resp.json().then(function(data) {
      let option;
      let ordered = {};

      Object.keys(data)
        .sort()
        .forEach(value => {
          ordered[value] = data[value];
        });
      console.log(ordered);

      Object.entries(ordered).forEach(([key, value]) => {
        option = document.createElement('option');
        option.value = key;
        option.text = value.regiao;
        dropdown.add(option);
      });
    });
  })
  .catch(function(err) {
    console.error('Error: ', err);
  });

Example of output:

10: {regiao: "Bogotá Colombia", name: "Bogotá", address: "Carrera 7 # 116 -50, Flormorado Plaza, Torre 1, We Work  – Bogotá-Colombia", phone: "+57 1 794 4883", fax: "", …}
11: {regiao: "Pequim China", name: "Pequim", address: "Room 1309 Office Tower 2, China Central Place,79 Jianguo Road, Beijing, 100025, China", phone: "+86 10 5969-5333", fax: "+86 10-5969-5123", …}
12: {regiao: "Xangai China", name: "Xangai", address: "Room 1716, 17th floor No. 818 Nanjing West Road, Shanghai – China", phone: "+86 21 5203-0368", fax: "", …}
13: {regiao: "Moscou Russia", name: "Moscou", address: "Smolenskaya Square 3, office 756, Moscow 121099, Russia", phone: "+7 495 967-7901", fax: "", …}
14: {regiao: "Bruxelas Belgica", name: "Bruxelas", address: "Avenue des Arts, 19 A/D, B-1000, Brussels – Belgium", phone: "+32 2211 0530", fax: "", …}
01: {regiao: "Dubai", name: "Dubai", address: "Jebel Ali Free Zone South JAFZA Job 19, Office 130… box 261901 – Dubai – UAE (Unitade Arab Emirates)", phone: "+971 4 885-5404", fax: "+971 4 885-5405", …}
02: {regiao: "Jerusalém", name: "Jerusalém", address: "3rd Floor, Gati Tower, Kiryat Hamada 3, Har Hotzvim, Jerusalem, P.O Box 45316", phone: "+9720732495829", fax: "", …}
03: {regiao: "Centro Oeste BR", name: "Brasília – DF", address: "Endereço: SAUN Quadra 05, Bloco C, Torre II, salas…o Empresarial CNC – CEP: 70.040-250 – Brasília-DF", phone: "+55 61 2027-0202", fax: "", …}
04: {regiao: "Nordeste BR", name: "Recife – PE", address: "Av. Engenheiro Antônio de Góes, 60 – Sala 604 – Ed…Trade Center – Pina – CEP: 51.010-000 – Recife-PE", phone: "+55 61 2027-0779", fax: "", …}
05: {regiao: "Norte BR", name: "Belém – PA", address: "Tv. Quintino Bocaiúva, 1588, Bloco B, 4º andar Naz…é, Ed. Sede da FIEPA – CEP: 66.035-190 – Belém-PA", phone: "+55 91 4009-4324", fax: "", …}
06: {regiao: "Sudeste BR", name: "São Paulo – SP", address: "Avenida Paulista n° 1313, 4º Andar, Sala 410-B, Ed. Sede da FIESP – CEP: 01311-923 – São Paulo-SP", phone: "+55 11 3549-4383", fax: "", …}
07: {regiao: "Sul BR", name: "Porto Alegre – RS", address: "Av. Assis Brasil 8787, bloco 2, FIERGS, Bairro Sarandi – CEP: 91.010-004 – Porto Alegre-RS", phone: "+55 51 3347-8718", fax: "", …}
08: {regiao: "São Francisco USA", name: "São Francisco", address: "2 Embarcadero Center, 8th Floor, San Francisco, CA 94111", phone: "+1 415 230-2181", fax: "", …}
09: {regiao: "Miami USA", name: "Miami", address: "Miami Center Building 201 South Biscayne Boulevard. Suite 1200 Miami FL 33131", phone: "+1 305 704-3500 / +1 305 704-3505"

I tried to user that code to sort the output but not this damage right:

Object.keys(data)
  .sort()
   .forEach(value => {
      ordered[value] = data[value];
 });

The data I am using in creating the options, is not all the result but the "id", which is the numbering and the region and I get this data without problems, nas como disse fira fora da ordem.

How can I resolve this issue?

  • 1

    I think this question seems similar to yours: https://answall.com/q/433431/8063 Take a look and get feedback here.

  • Sort by region?

  • Not that question is not the same doubt I was having, but I was able to solve it. I removed the 0 from item 1 through 9 and it worked. But thank you all.

2 answers

2

The position of keys in Objects is not guaranteed in Javascript, that is the role of arrays. In practice, in your code you are already working with an array when you use Object.values() so it would be best to always use array and sort this array by the Ids of these objects within the array.

You could do it like this:

fetch(URL)
  .then(function(resp) {
    if (resp.status !== 200) {
      console.warn('Error: ' + resp.status);
      return;
    }

    resp.json().then(function(data) {
      Object.keys(data)
        .map(key => {
          const option = {
            option.value: Number(key), // converte em numero para facilitar a ordenação
            option.text: value.regiao
          }
        })
        .sort((a, b) => a.value - b.value) // ordenar a array
        .forEach(({value, text}) => {
          option = document.createElement('option');
          option.value = value;
          option.text = text;
          dropdown.add(option);
        });
    });
  })
  .catch(function(err) {
    console.error('Error: ', err);
  });

1

I believe that you can simplify logic a little and at the same time, as the already mentioned suggestion, you should not believe that the Keys of your object will order your options. You could simplify your json object a bit for a list that contains something like this:

[
    {
        "regiao": "Dubai",
        "name": "Dubai",
        "address": "Jebel Ali Free Zone South JAFZA Job 19, Office 1301, P.O. box 261901 – Dubai – UAE (Unitade Arab Emirates)",
        "phone": "+971 4 885-5404",
        "fax": "+971 4 885-5405",
        "email": "[email protected]",
        "ordem": 2, // atributo para poder ordernar suas options
        "valor": "002", // valor que quer atribuir a option, poderia ser ate mesmo o nome da "regiao" ou "nome"
    },
    {
        "regiao": "Centro Oeste BR",
        "name": "Brasília – DF",
        "address": "Endereço: SAUN Quadra 05, Bloco C, Torre II, salas 1201 a 1701 – Centro Empresarial CNC – CEP: 70.040-250 – Brasília-DF",
        "phone": "+55 61 2027-0202",
        "fax": "",
        "email": "[email protected]",
        "time": "9:00 às 18:30",
        "ordem": 1,
        "valor": "001",
    },
];

However, follow my suggestion to resolve your question, and I hope to have helped!

function makeOption(item, key) {
    const option = document.createElement("option");
    option.text = item.regiao;
    option.value = key;
    return option;
}

fetch(URL)
    .then(function(resp) {
        if (resp.status !== 200) {
            console.warn("Error: " + resp.status);
            return;
        }

        const data = await resp.json(); // espera pela promise aque que resolva.

        Object.keys(data).forEach((key) => {
            const option = makeOption(data[key], key);
            dropdown.add(option);
        };

    })
    .catch(function(err) {
        console.error("Error: ", err);
    });
  • Thank you Caio, I think you are right in simplifying the json and I will apply your suggestion to remove the "ID" you had created and create the order field and I will study your code to improve mine. Thanks for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.