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!

3
  • First, use JSON.parse, not eval Commented Feb 1, 2018 at 20:15
  • var s_obj = JSON.parse(messageBody); Commented Feb 1, 2018 at 20:15
  • That is not a string. Nor is it valid JavaScript. Except for the document.write(str) piece and the lack of surrounding quotes it looks like JSON. (In which case, you would do JSON.parse('[{"company":1,...}])) Commented Feb 1, 2018 at 20:15

1 Answer 1

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`);
    }
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.