Home > other >  How to get number of doubling propreties in object javascript
How to get number of doubling propreties in object javascript

Time:10-01

im trying to make o loop in an object json so that it can show me all the doubling of the propreties.

This is my JSON file (departements-list.json):

 [
        {"Departement": "meryem"},
        {"Departement": "meryem"},
        {"Departement": "meryem"},
        {"Departement": "meryem"},
        {"Departement": "meryem"},
    
        {"Departement": "sara"},
        {"Departement": "sara"},
        {"Departement": "sara"},
    
        {"Departement": "ouss"},
        {"Departement": "ouss"},
        {"Departement": "ouss"},
    
        {"Departement": "samati"},
        {"Departement": "samati"},
        {"Departement": "samati"},
        {"Departement": "samati"},
        {"Departement": "samati"},
        {"Departement": "samati"},
        {"Departement": "samati"},
        {"Departement": "samati"},
        {"Departement": "samati"}
   ]

And this is my js :

  import departement_list from "../data/departements-list.json";
    var jsonData = JSON.parse(JSON.stringify(departement_list));
    
    for (var dep of jsonData) {
     let nb_dep = Object.keys(dep.Departement).length;
    
      console.log(dep.Departement, " =" , nb_dep);
    }

I had this result in the browser console :

meryem  = 6
3custom-map.js:20 sara  = 4
3custom-map.js:20 ouss  = 4
9custom-map.js:20 samati  = 6

Which is not logical !

CodePudding user response:

This is an example of how to get the number of occurrences for each department value. I first map the data to be a list of the department values. Then I create a new set to create an array of each value. Then I loop through each unique value, and filter the data by that value, and log the length or number of occurrences for each value.

const jsonData = [
  {"Departement": "meryem"},
  {"Departement": "meryem"},
  {"Departement": "meryem"},
  {"Departement": "meryem"},
  {"Departement": "meryem"},

  {"Departement": "sara"},
  {"Departement": "sara"},
  {"Departement": "sara"},

  {"Departement": "ouss"},
  {"Departement": "ouss"},
  {"Departement": "ouss"},

  {"Departement": "samati"},
  {"Departement": "samati"},
  {"Departement": "samati"},
  {"Departement": "samati"},
  {"Departement": "samati"},
  {"Departement": "samati"},
  {"Departement": "samati"},
  {"Departement": "samati"},
  {"Departement": "samati"}
];

const dataValues = jsonData.map(data => data.Departement);
const uniqueValues = [...new Set(dataValues)];
for (const val of uniqueValues) {
  console.log(`
    Val ${val}
    has ${dataValues.filter(v => v == val).length} entries
  `);
}

  • Related