0

I store the result of my Flask server in this.state.jsondata and it's a JSON like this {label{},text{}}

export default class Success extends React.Component {

    constructor(props) {
        super();
        if (props.location.state) {
            this.state = {
                jsondata: props.location.state.referrer,
                upload: true
                
            } //put jsons data in state object
            toast.success('Upload success')
        } else {
            this.state = {
                upload: false
            }
        }
    }    
...

So in order to find occurrence in label I converted my JSON to an Array and coded something to find the occurrences but my problem is that I want to find the occurrence of 0, 1 and 2 not only 0. You can already see that I'll need to duplicate my code three times and it's a no-go.

render() {
        const arr = []
        Object.keys(this.state.jsondata.label).forEach(key => arr.push({id: key, value: this.state.jsondata.label[key]}))
        
        var search = 0;
        var count = arr.reduce(function(n, val) {
            return n + (val.value === search);
        }, 0);
...

How can I modify my code to be able to get occurrence of a given number ?

Here is the whole code: https://jsfiddle.net/p9qxktgz/3/

[EDIT]

this.state.jsondata looks like this :

{
   "label":{
      "0":0,
      "1":0,
      "2":0,
      "3":0,
      "4":0
   },
   "text":{
      "0":"- Awww, c'est un bummer. Tu devrais avoir david carr du troisième jour pour le faire. ;ré",
      "1":"Est contrarié qu'il ne puisse pas mettre à jour son facebook en le télémaignant ... et peut-être pleurer en conséquence, l'école aujourd'hui aussi. blabla!",
      "2":"J'ai plongé plusieurs fois pour la balle. A réussi à économiser 50% le reste sort de limites",
      "3":"Tout mon corps a des démangeaisons et comme si c'était en feu",
      "4":"Non, il ne se comporte pas du tout. je suis en colère. pourquoi suis-je ici? Parce que je ne peux pas vous voir partout."
   }
}

the arr is like this : test

There isn't a "expected" output, all I want to do is to be able to get as an output the occurrence of each diffrent values in arr

Jérôme Vial
  • 15
  • 1
  • 5

1 Answers1

0

const jsonInput = {
   "label":{
      "0":0,
      "1":0,
      "2":0,
      "3":0,
      "4":0
   }
   }

const occurrenceMap = Object.values(jsonInput.label).reduce((finalMap, item) => {
  finalMap[item] = ++finalMap[item] || 1; 
  
  return finalMap;
} , {})

console.log(occurrenceMap)
Shyam
  • 5,292
  • 1
  • 10
  • 20
  • edited the answer to get the occurrence from the json directly instead of converting it into an array and then using that to find the occurrence it . – Shyam Jun 02 '21 at 18:31