在淘汰赛中将 JSON 数据转换为 Javascript 数组
Posted
技术标签:
【中文标题】在淘汰赛中将 JSON 数据转换为 Javascript 数组【英文标题】:Convert JSON data to Javascript Array in knockout 【发布时间】:2021-02-22 05:48:56 【问题描述】:我有以下 JSON 数组:
AccessToFinancialServicesRule: Clean: 3, Copy: 3
BoardParticipationRule: Clean: 3, Copy: 3
Documents: null
EconomicDevelopmentRule: Clean: 3, Copy: 3
EmployeeStructureRule: Clean: 3, Copy: 3
EmpowermentFinanceRule: Clean: 3, Copy: 3
EnterpriseDevelopmentRule: Clean: 3, Copy: 3
OwnershipRule: Clean: 3, Copy: 3
PreferentialProcurementRule: Clean: 3, Copy: 3
ResponsibleSocialMarketingRule: Clean: 3, Copy: 3
SkillsDevelopmentRule: Clean: 3, Copy: 3
SocioEconomicDevelopmentRule: Clean: 3, Copy: 3
SupplierDevelopmentRule: Clean: 3, Copy: 3
我正在尝试将其转换为如下所示的数组
0: label: "Ownership", clean: 3, copy: 3
1: label: "Skills<br>Development", clean: 3, copy: 3
2: label: "Localisation", clean: 3, copy: 3
3: label: "Socio-Economic<br>Development", clean: 3, copy: 3
4: label: "Board Participation", clean: 3, copy: 3
5: label: "Employee Structure", clean: 3, copy: 3
6: label: "Preferential Procurement", clean: 3, copy: 3
7: label: "Enterprise Development", clean: 3, copy: 3
8: label: "Supplier Development", clean: 3, copy: 3
其中每个项目都称为label
并显示clean
和copy
我尝试了以下方法:
var allItems = [data.Mappings];
var testData = allItems.map(function(item)
return
'label': item,
'clean': item.Clean,
'copy':item.Copy
;
);
console.log(testData)
但这似乎不起作用,它将所有东西都变成这样的一个对象:
0:
clean: undefined
copy: undefined
label: OwnershipRule: …, BoardParticipationRule: …, SkillsDevelopmentRule: …, EmployeeStructureRule: …, PreferentialProcurementRule: …, …
我做错了什么?
【问题讨论】:
你的数据不是数组,你的意思是它是一个对象数组吗? @netizen 是对象数组 【参考方案1】:您需要使用Object.keys
来访问对象中的属性,这是一个示例:
const convertToArray = array.map((item) =>
const key = Object.keys(item)
if (item[key])
return
label: key[0],
clean: item[key].Clean,
copy: item[key].Copy
)
完整示例请查看链接:https://jsfiddle.net/qgwxbuem/
【讨论】:
Object.keys 返回一个数组,加 [0] 或 .shift() 它现在可以工作了,虽然我会把它放在 key 的赋值上,因为下一行仍然检查数组以上是关于在淘汰赛中将 JSON 数据转换为 Javascript 数组的主要内容,如果未能解决你的问题,请参考以下文章