gpt4 book ai didi

javascript - 将重复出现的 JSON 名称转换为对象?

转载 作者:行者123 更新时间:2023-11-30 07:49:59 25 4
gpt4 key购买 nike

我有以下字符串...

{
"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++;
}

最佳答案

您可以拆分键并通过行走给定对象来减少路径。

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

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);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 将重复出现的 JSON 名称转换为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54691770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com