Javascript - 将字符串转换为关联数组并按值汇总

Javascript - convert string to associative array and summarize by value

这是我第一次使用 javascript。我有以下字符串:

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}]

我需要转换这个字符串,以便我根据 number_employees 将它们总结如下:

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

我目前正在努力将字符串转换为 javascript 对象。一旦我有了关联数组,我就可以将它转换成地图并计算 number_employees.

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

这给我以下错误:

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

任何 help/hint/guidance 将不胜感激!

对您的数据做出一些假设,您可以尝试这样的事情:

首先,使用 JSON 对象将 JSON 字符串转换为对象,然后在您尝试使用 Array.prototype.reduce 进行总结时 - (您将参数颠倒过来)

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