Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert data formats in javascript

I am trying to get a paragraph and turn it into words and also realize the frequency of each.

var pattern = /\w+/g,
  string = "mahan mahan mahan yes yes no",
  matchedWords = string.match(pattern);

/* The Array.prototype.reduce method assists us in producing a single value from an
   array. In this case, we're going to use it to output an object with results. */
var counts = matchedWords.reduce(function(stats, word) {

  /* `stats` is the object that we'll be building up over time.
     `word` is each individual entry in the `matchedWords` array */
  if (stats.hasOwnProperty(word)) {
    /* `stats` already has an entry for the current `word`.
       As a result, let's increment the count for that `word`. */
    stats[word] = stats[word] + 1;
  } else {
    /* `stats` does not yet have an entry for the current `word`.
       As a result, let's add a new entry, and set count to 1. */
    stats[word] = 1;
  }

  /* Because we are building up `stats` over numerous iterations,
     we need to return it for the next pass to modify it. */
  return stats;

}, {})

var dict = []; // create an empty array
// this for loop makes a dictionary for you
for (i in counts) {
  dict.push({
    'text': i
  });
  dict.push({
    'size': counts[i]
  });

};

/* lets print and see if you can solve your problem */
console.log(dict);

the dict variable returns:

[ { text: 'mahan' },{ size: 3 },{ text: 'yes' },{ size: 2 },{ text:'no'},{ size: 1 } ]

but I am using a data visualization code and i need to turn the result into something like this:

[ { "text": "mahan" , "size": 3 },{ "text: "yes", size: 2 },{ "text":'no', "size": 1 } ]

I know it is basic but I am just an artist trying to use some code for a project. I appreciate your help.

like image 696
Mahanmeh Avatar asked Jun 06 '26 15:06

Mahanmeh


1 Answers

simply do:

dict.push({'text':i, "size": counts[i]});
like image 74
asdf_enel_hak Avatar answered Jun 09 '26 04:06

asdf_enel_hak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!