[英]JSON to Multidimensional Javascript Object
I'm loading an external JSON file into javascript, the JSON file looks like this: 我正在将外部JSON文件加载到javascript中,JSON文件如下所示:
[
{
"name":"Apple",
"year":8,
"records_lost":12367232
},
{
"name":"178.com",
"year":7,
"records_lost":10000000
},
{
"name":"Accendo Insurance Co. ",
"year":7,
"records_lost":175350
}
]
Eventually, I want to access the data via a Javascript object like this (don't mind the syntax). 最终,我想通过这样的Javascript对象访问数据(不要介意语法)。 The point is that name will be a parent with its own meta-data.
关键是该名称将是具有其自己的元数据的父项。
"Apple":
"year":8,
"records_lost":12367232
"178.com":
"year":7,
"records_lost":10000000
This is the code I've already written for this part, which doesn't make name parent yet and only saves the last row of the JSON file into the array ( +=
instead of =
would fix this, but delivers ugly values, obviously). 这是我已经为该部分编写的代码,它还没有使名称成为父项,而仅将JSON文件的最后一行保存到数组中(
+=
代替=
可以解决此问题,但提供难看的值,显然)。
function initJSON() {
loadJSON(function(response) {
var JSONParse = JSON.parse(response);
var i;
for (i in JSONParse) {
JSONdata.name.i = JSONParse[i].name;
JSONdata.year = JSONParse[i].year;
JSONdata.recl = JSONParse[i].records_lost;
}
});
}
initJSON();
Thanks in forward. 谢谢前进。
it should be : 它应该是 :
var i;
for (i in JSONParse) {
JSONdata.name = i.name;
JSONdata.year = i.year;
JSONdata.recl = i.records_lost;
}
unless your loop was different: 除非您的循环不同:
var i;
for (i = 0; i < JSONParse.length; i++) {
JSONdata.name = JSONParse[i].name;
JSONdata.year = JSONParse[i].year;
JSONdata.recl = JSONParse[i].records_lost;
}
Try utilizing Array.prototype.map()
, delete
operator 尝试利用
Array.prototype.map()
, delete
运算符
var data = [{ "name": "Apple", "year": 8, "records_lost": 12367232 }, { "name": "178.com", "year": 7, "records_lost": 10000000 }, { "name": "Accendo Insurance Co. ", "year": 7, "records_lost": 175350 }]; var res = data.map(function(val, key) { var obj = {}; obj[val.name] = val; delete obj[val.name].name; return obj }); document.getElementsByTagName("pre")[0].textContent = JSON.stringify(res, null, 4);
<pre></pre>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.