如何操作此字符串并组合重复键的值?

时间:2018-04-26 03:04:02

标签: jquery string loops

我有一个对象数组形式的字符串。

var str_obj = `[
    {
        "STUDENT_ID": "ST001",
        "MAJOR": "SCIENCE",
        "STATUS": "1"
    },
    {
        "STUDENT_ID": "ST002",
        "MAJOR": "SCIENCE",
        "STATUS": "1"
    },
    {
        "STUDENT_ID": "ST002",
        "MAJOR": "HISTORY",
        "STATUS": "1"
    },
    {
        "STUDENT_ID": "ST002",
        "MAJOR": "MATH",
        "STATUS": "1"
    },
    {
        "STUDENT_ID": "ST003",
        "MAJOR": "HISTORY",
        "STATUS":"2"
    }
]`;

我想要做的是操纵此字符串并组合相同STUDENT_ID的值。操纵字符串的输出应为:

var str_obj_combined = `[
    {
        "STUDENT_ID": "ST001",
        "MAJOR": "SCIENCE",
        "STATUS": "1"
    },
    {
        "STUDENT_ID": "ST002",
        "MAJOR": "SCIENCE,HISTORY,MATH",
        "STATUS":"1,1,2"
    },
    {
        "STUDENT_ID": "ST003",
        "MAJOR": "HISTORY",
        "STATUS": "2"
    }
]`;

输出也应该是字符串格式为对象数组。

我看过this很好的答案,但我仍然没有理解如何实现解决方案,因为我必须操纵字符串而不是对象数组。

2 个答案:

答案 0 :(得分:1)

您可以使用JSON.parse将json(字符串)转换为对象数组。使用reduce将数组汇总到一个对象中。使用Object.values将对象再次转换为数组。要加入mapMAJOR

的数组STATUS

如果您希望str_obj_combined成为字符串,则可以使用JSON.stringify

不需要jQuery。您可以在没有任何js库的情况下执行此操作。

var str_obj = '[{"STUDENT_ID":"ST001","MAJOR":"SCIENCE","STATUS":"1"},{"STUDENT_ID":"ST002","MAJOR":"SCIENCE","STATUS":"1"},{"STUDENT_ID":"ST002","MAJOR":"HISTORY","STATUS":"1"},{"STUDENT_ID":"ST002","MAJOR":"MATH","STATUS":"1"},{"STUDENT_ID":"ST003","MAJOR":"HISTORY","STATUS":"2"}]';

var str_obj_combined = Object.values(JSON.parse(str_obj).reduce((c, {STUDENT_ID,MAJOR,STATUS}) => {
  c[STUDENT_ID] = c[STUDENT_ID] || {STUDENT_ID: STUDENT_ID,MAJOR: [],STATUS: []}
  c[STUDENT_ID].MAJOR.push(MAJOR);
  c[STUDENT_ID].STATUS.push(STATUS);
  return c;
}, {})).map(o => {
  o.MAJOR = o.MAJOR.join();
  o.STATUS = o.STATUS.join();
  return o;
});


str_obj_combined = JSON.stringify(str_obj_combined); //Optional. Convert the array of objects into string

console.log(str_obj_combined);

答案 1 :(得分:0)

对于您的问题,您只需使用JSON.parse()方法将字符串解析为数组。

JSON.parse('[{"STUDENT_ID":"ST001","MAJOR":"SCIENCE","STATUS":"1"},{"STUDENT_ID":"ST002","MAJOR":"SCIENCE","STATUS":"1"},{"STUDENT_ID":"ST002","MAJOR":"HISTORY","STATUS":"1"},{"STUDENT_ID":"ST002","MAJOR":"MATH","STATUS":"1"},{"STUDENT_ID":"ST003","MAJOR":"HISTORY","STATUS":"2"}]')