简体   繁体   English

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

[英]Javascript - convert string to associative array and summarize by value

This is the first time I am working with javascript. 这是我第一次使用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: 我需要转换此字符串,以便根据number_employees对其进行汇总,如下所示:

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

I am currently struggling to convert the string into javascript object. 我目前正在努力将字符串转换为javascript对象。 Once I have the asscoiative array, I can convert it into map and count the number_employees . 一旦有了关联数组,就可以将其转换为map并计算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) 首先,使用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`); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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