将重复的JSON名称转换为对象?

时间:2019-02-14 13:39:05

标签: javascript jquery json

我有以下字符串...

{
    "Qualifications[0].DegreeType": "Degree Type 1",
    "Qualifications[0].Classification": "Clasification 1",
    "Qualifications[0].CourseTitle": "Course Title 1",
    "Qualifications[0].YearOfAward": "2018",
    "Qualifications[0].AwardingInstitution": "Awarding institution 1",
    "Qualifications[1].DegreeType": "Degree Type 2",
    "Qualifications[1].Classification": "Classification 2",
    "Qualifications[1].CourseTitle": "Course Title 2",
    "Qualifications[1].YearOfAward": "2019",
    "Qualifications[1].AwardingInstitution": "Awarding Institution 2",
    ... and so on...
 }

有人知道有一种简单的方法可以将其转换为javascript对象,这样我就可以有效地进行操作...

$(Qualifications).each(i, v){
    //do stuff on whatever property of Qualifications[i]
}

我能想到的唯一方法是使用字符串操作以及类似下面的内容,但是它需要为每个属性使用大量自定义代码检查映射,而我正在寻找更通用,更简单的方法。...

    let i = 0;
    while (Qualifications[" + i +"].whateverProperty..) {
        //add to object array
        i++;
    }

2 个答案:

答案 0 :(得分:5)

您可以通过移动给定的对象来拆分键并减少路径。

如果不存在对象,请使用名称或数组创建一个新属性。稍后分配值。

DbSet.SqlQuery()
DbContext.Database.SqlQuery()
DbContext.Database.ExecuteSqlCommand()
function setValue(object, path, value) {
    var way = path.replace(/\[/g, '.').replace(/\]/g, '').split('.'),
        last = way.pop();

    way.reduce(function (o, k, i, kk) {
        return o[k] = o[k] || (isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {});
    }, object)[last] = value;
}

var object = {
        "Qualifications[0].DegreeType": "Degree Type 1",
        "Qualifications[0].Classification": "Clasification 1",
        "Qualifications[0].CourseTitle": "Course Title 1",
        "Qualifications[0].YearOfAward": "2018",
        "Qualifications[0].AwardingInstitution": "Awarding institution 1",
        "Qualifications[1].DegreeType": "Degree Type 2",
        "Qualifications[1].Classification": "Classification 2",
        "Qualifications[1].CourseTitle": "Course Title 2",
        "Qualifications[1].YearOfAward": "2019",
        "Qualifications[1].AwardingInstitution": "Awarding Institution 2"
    },
    result = {};

Object.entries(object).forEach(([k, v]) => setValue(result, k, v));

console.log(result);

答案 1 :(得分:1)

您可以像这样简单地使用标准Object.keys

 let qualifications = []
 const my_object = {
    "Qualifications[0].DegreeType": "Degree Type 1",
    "Qualifications[0].Classification": "Clasification 1",
    "Qualifications[0].CourseTitle": "Course Title 1",
    ...
 }


Object.keys(my_object).forEach(key => {
    //to access the index you could then do:
    const idx = Number(key.split('[')[1].split(']')[0])
    const sub_key = key.split('.')[1]
    //not here that i don't verify if the index exists
    if (!qualifications[idx]) qualifications[idx] = {}
    qualifications[idx][sub_key] = my_object[key]
})