gpt4 book ai didi

javascript - javascript中循环对象的问题

转载 作者:行者123 更新时间:2023-11-28 18:51:34 25 4
gpt4 key购买 nike

我的 JavaScript 有一些问题

<html>
<body>
<p id="demo2"></p>
<script>
var text = '{"h":["username","hair_color","height"],"d":[["ali","brown",1.2],["ma0072c","blue",1.4],["joe","brown",1.7],["zehua","black",1.8]]}';

var obj = JSON.parse(text);
var x= Object.keys(obj.h).length;
var y= Object.keys(obj.d).length;

var json_datas = JSON.stringify(obj.h);
var json_data = JSON.stringify(obj.d);
var obj2 = JSON.parse(json_data);
var json_data2 = JSON.stringify(obj2[1]);
var obj3 = JSON.parse(json_data2);
var newjson = [];
var newjson2 = [];
i=0;
l=0;
z=0;
m=0;
var boys= {};
for (i in obj.h){
boys[obj.h[i]] = obj.d[m][l];
l++;
z++;
m++;
newjson.push(boys);
}
newjson2 = newjson2.concat(newjson);
var newjson2 = JSON.stringify(newjson);
document.getElementById("demo2").innerHTML = newjson2;
</script>
</body>
</html>

这个脚本boys[obj.h[i]] = obj.d[m][l];

为什么代码不想循环?有人能告诉我正确的循环吗?我想要这样的输出

[{"username":"ali","hair_color":"brown","height":1.2},
{"username":"marc","hair_color":"blue","height":1.4},
{"username":"joe","hair_color":"brown","height":1.7},
{"username":"zehua","hair_color":"black","height":1.8}]

但是我现在的输出是这样的

[{"username":"ali","hair_color":"brown","height":1.2},
{"username":"ali","hair_color":"brown","height":1.2},
{"username":"ali","hair_color":"brown","height":1.2},
{"username":"ali","hair_color":"brown","height":1.2}]

最佳答案

我建议将循环代码改进为如下所示:

var newjson2 = [];
obj.d.forEach(function(element) {
var k = {};
element.forEach(function(element, i){
k[obj.h[i]] = element;
})
newjson2.push(k);
})

对我来说看起来更清晰、更稳健......

关于javascript - javascript中循环对象的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34452517/

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