0

This is the first time I am working with javascript. I have the following string:

document.write(str)
[{"company":1,"number_employees":5},
{"company":4,"number_employees":25},
{"company":5,"number_employees":5},
{"company":2,"number_employees":5},
{"company":4,"number_employees":25}]

I need to convert this string such that I summarize them according to the number_employees as follows:

Three companies have number_employees=5 and two companies have number_employees=25

I am currently struggling to convert the string into javascript object. Once I have the asscoiative array, I can convert it into map and count the number_employees.

s_obj = eval('({' + messageBody + '})');
var result = s_obj.reduce(function(map, obj) {
    map[obj.key] = obj.val;
    return map;
}, {});

This is giving me the following error:

VM181:1 Uncaught SyntaxError: Unexpected token ,
at onMessage ((index):41)
at WebSocket.<anonymous> (stomp.min.js:8)

Any help/hint/guidance would be much appreciated!

Mooni
  • 121
  • 12

1 Answers1

1

Making a couple of assumptions about your data, you might try something like this:

First, convert the JSON string into an Object using the JSON Object, then as you were attempting use Array.prototype.reduce to summarize - (you have the arguments reversed)

var summary = {};
var messageBody = '[{"company":1,"number_employees":5},{"company":4,"number_employees":25},{"company":5,"number_employees":5},{"company":2,"number_employees":5},{"company":4,"number_employees":25}]';

JSON.parse(messageBody).reduce( (acc, cur) => {
    acc[cur.number_employees] = (acc[cur.number_employees] || 0) + 1;
    return acc;
}, summary);
for(entry of Object.keys(summary)) {
    if (summary.hasOwnProperty(entry)) {
        console.log(`There are ${summary[entry]} companies with ${entry} employees`);
    }
}
Tibrogargan
  • 4,508
  • 3
  • 19
  • 38