Create JSON files relating arrays

Asked

Viewed 481 times

0

I have two json files, one with id, status and acronym and the other with the state id and the cities of that state. I read these files and recorded the content in arrays, but I need to create a file for each state with their respective cities, relating the ids. So far I was able to create the files separated by state in the first FOR, but I’m in doubt about how to put each city in their content, I was only able to create the files and the initial structure of JSON:

Example file that has to be created:

ES.json

[{
    "ID": "1",
    "Nome": "Afonso Cláudio",
},
     {
    "ID": "2",
    "Nome": "Água Doce do Norte",
},
     {
    "ID": "3",
    "Nome": "Águia Branca",
},
]

All these cities are part of ES, so I need a file for each state and its respective cities.

Link to the Json files

var fs = require("fs");

let dataStates = fs.readFileSync("Estados.json", "utf8");

let states = JSON.parse(dataStates);
let sigla = states.map((state) => {
  const { ID, Sigla, Nome } = state;
  return {
    idstate: ID,
    sigla: Sigla,
    estadoNome: Nome,
  };
});
//console.log(sigla);

let dataCities = fs.readFileSync("Cidades.json", "utf8");

let cities = JSON.parse(dataCities);
let nome = cities.map((city) => {
  const { ID, Nome, Estado } = city;
  return {
    idcity: ID,
    cidadeNome: Nome,
    cidadeEstado: Estado,
  };
});
//console.log(nome);

const initialJson = {
  nextId: 1,
  cidades: [],
};

for(i = 0; i < sigla.length; i++){
  fs.writeFileSync(sigla[i].sigla + '.json', JSON.stringify(initialJson));

    for(l = 0; l < nome.length; l++){
      cidades = { id: nextId++, name: nome[l].cidadeNome };
      cidades.push(cidades);
      fs.writeFileSync(sigla[i].sigla + '.json', JSON.stringify(cidades));
}
}
  • An example of the two files was missing. The way it is, we have to interpret its code to try to reverse engineer it and figure out what’s in them. It seems too much work, no?

  • I pasted some images to facilitate understanding

  • You can’t copy and paste from one json in an image. Learn more about this in: How NOT to Ask Questions Manual - Post Code as Image.

  • I put the link to the files

  • 1

    Also give an example of one of the status files that should be generated. You don’t have to have every city, just an example with a couple of cities is already good size.

  • You can give an example of the output result?

  • I put an example there, basically I need to create a file for each state, with the acronym as name and their respective cities as content, I don’t know if the example was good but something better.

Show 2 more comments

1 answer

3


  • Separate cities by groups using the function reduce resulting in the creation of a Map grouping cities by state;

  • Walk the array of states obtaining all the cities of each of the Map previously created through the function Map.get;

  • Save the value obtained in the last item with the function fs.writeFileSync.


const fs = require('fs');

const cidades = require('./Cidades.json');
const estados = require('./Estados.json');

const mapear = (resultado, { Estado: estado, ...cidade }) => {
  const acumulador = resultado.get(estado) || [];

  return resultado.set(estado, [...acumulador, cidade]);
};

const salvar = (mapa, { ID: id, Sigla: sigla }) => {
  fs.writeFileSync(`${sigla}.json`, JSON.stringify(mapa.get(id), null, 2));
};

const mapa = cidades.reduce(mapear, new Map());
estados.forEach((estado) => salvar(mapa, estado));

reduce

The method reduce() performs a function reducer (provided by you) for each member of the array, resulting in a single return value.

Example:

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15


Map

The object Map is a simple key/value map.


Map.get

The method get() returns a specific element of an object of Map.

Browser other questions tagged

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