我做了一个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...
所以我想忽略"数据中的第一个数组"数组,使用第二个数组的值作为键(并用更有用的东西替换空字符串),并将所有剩余数组中的值作为结果对象中的值。
所以这是多部分问题,尽管我怀疑是一个相当简单的问题。最简单的方法是什么 - 如果不同,在处理/页面加载方面最简单的方法是什么?
提前致谢,
答案 0 :(得分:2)
- 你应该构建一个有意义的对象!
醇>
<ion-col class="col" col-6="">
<playlist ng-reflect-data="[object Object]"><div class="playlist">
<span class="span-icon"><ion-icon name="ios-star-outline" role="img" class="icon icon-md ion-ios-star-outline" aria-label="star outline" ng-reflect-name="ios-star-outline"></ion-icon></span>
<span>My Favorites</span>
<img src="./assets/images/img2.jpg" alt="My Favorites">
</div></playlist>
</ion-col>
const meaningful_objs = {
"Location": "",
"Passes": "",
"Passes%": "",
"No ID": "",
"No ID%": "",
"Fails": "",
"Fails%": "",
"Fail Dangerous": "",
"Fail Dangerous%": "",
"Total": ""
};
// or get it from you data[1],
// but I think it has some errors of you got returned data!
// It should be have all keys!
// just make a assume, you get the right data[1]!
const data[1] = ["Location", "Passes", "Passes%", "No ID", "No ID%", "Fails", "Fails%", "Fail Dangerous", "Fail Dangerous%", "Total"];
let keys = data[1];
答案 1 :(得分:1)
您可以将第二个数组作为所需对象的键,并仅在键之后迭代该部分。然后迭代键并为数组的值构建一个新对象。返回对象以便为新数组进行映射。
var data = { data: [["2016 Pass/Fail Rates by Test Centre", "", "", "", "", "", "", "", "", ""], ["Location", "Passes", "Passes%", "No ID", "No ID%", "Fails", "Fails%", "Fail Dangerous", "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"]] },
keys = data.data[1],
result = data.data.slice(2).map(function (a) {
var temp = {};
keys.forEach(function (k, i) {
temp[k] = a[i];
})
return temp;
});
console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 2 :(得分:1)
您可以在将索引和值添加到对象中时迭代数组...
您可以找到有关如何迭代对象和数组的示例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);