简体   繁体   中英

Javascript - convert string to associative array and summarize by value

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM