这是我第一次使用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对象。一旦我有了asscoiative数组,我就可以将它转换为map并计算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)
非常感谢任何帮助/提示/指导!
答案 0 :(得分:1)
对您的数据做一些假设,您可以尝试这样的事情:
首先,使用JSON对象将JSON字符串转换为Object,然后在尝试使用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`);
}
}
&#13;