gpt4 book ai didi

javascript - 将数组值转换为对象键

转载 作者:数据小太阳 更新时间:2023-10-29 04:39:50 25 4
gpt4 key购买 nike

我做了一个 get,它返回一个 json 对象,如下所示:

"data": [
[
"2016 Pass/Fail Rates by Test Centre",
"",
"",
"",
"",
"",
"",
"",
"",
""
],
[
"",
"Passes",
"",
"No ID",
"",
"Fails",
"",
"Fail Dangerous",
"",
"Total"
],
[
"Sometown",
"8,725",
"53.40%",
"140",
"0.90%",
"7,417",
"45.40%",
"48",
"0.30%",
"16,330"
],
[
"Some Other Town",
"12,778",
"44.80%",
"193",
"0.70%",
"15,422",
"54.10%",
"103",
"0.40%",
"28,496"
],
[...many more identically formatted arrays...]

最后我想:

[{
"Location": "Sometown",
"Passes": 8,
725,
"Pass%": 53.40 % ,
"No ID": 140,
"NoID%": 0.90 % ,
"Fails": 7,
417,
"Fail%": 45.40 % ,
"Fail Dangerous": 48,
"FailDangerous%": 0.30 % ,
"Total": 16,
330
}, {
"Location": "Some Other Town",
"Passes": 8,
725,
etc etc...

所以我想忽略“数据”数组中的第一个数组,使用第二个数组的值作为键(并用更有用的东西替换空字符串),并将所有剩余数组中的值作为结果中的值对象。

所以这是一个多部分问题,尽管我怀疑这是一个相当简单的问题。最简单的方法是什么 - 如果不同,在处理/页面加载方面最精简的方法是什么?

提前致谢

最佳答案

您可以在将索引和值添加到对象中时遍历数组...

您可以找到有关如何迭代对象和数组的示例 here和一个例子 here

Generally, to add an item to object

var array = [{"Location":"Sometown"}, {"Location2":"Sometown2"},    {"Location3":"Sometown3"}],
object = {};
array.forEach(function(element, index) {
object[index] = element;
});
console.log(object);

关于javascript - 将数组值转换为对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43137010/

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