Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

93
Visualizações
How can I get an output like [item: 'value1', item:'value2', ...] in an array of objects in Javascript?

I'm trying to convert a JSON (a list of countries/cities in the world) to an array, and what I'm trying to do with the array is:

  1. Leave only the name of the countries
  2. Since many of the countries are repeated, only leave them once

I was able to achieve this thanks to this function (just to clarify: in the final project, fetchData is imported from another file and the variable declaration and the array are in a document.addEventListener("DOMContentLoaded", async () => {}, this is just one for testing purposes)

async function fetchData(url) {
  const response = await fetch(url);
  return await response.json();
}

(async () => {
  let worldCities = await fetchData(
    "https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json"
  );

  const countries = [...new Set(worldCities.map((item) => item.country))];

  console.log(countries);
})();
.as-console-wrapper { max-height: 100% !important; top: 0; }

With fetchData I asynchronously request a resource (the URL of the .json file), then I map an array with the file and "filter" it as I mentioned above

But the problem is that it works, but not as needed, because the output should be like this

desired result

and my output is just an array of country names

I know that I'm mapping (only) the current value required with worldCities.map((item) => item.country) and removing repeated values with [...new Set()]

But how could I make the array returns an object like key/value pairs [country: 'country1', country: 'country2', ...] (or something similar to the output of the image) instead of the normal array ['country1', 'country2', ...]?

Any help is welcome, thank you very much!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

map() it again:

const countries = [...new Set(worldCities.map((item) => item.country))].map(country => ({ country }))

Working solution:

async function fetchData(url) {
  const response = await fetch(url);
  return await response.json();
}

(async () => {
  let worldCities = await fetchData(
    "https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json"
  );

  const countries = [...new Set(worldCities.map((item) => item.country))].map(country => ({ country }))

  console.log(countries);
})();
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

By giving it the approach below, you can achieve to get an array of unique country names. If you want an array of country objects, then you can convert the names array.

$.get('https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json', function(data) {
    var res = JSON.parse(data)             
    var countries = res.map(function(elem){return elem.country});  
    const uniques = Array.from(new Set(countries));
    console.log(uniques)
 });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda