我想使用JavaScript或jQuery从两个数组创建一个Json对象。数据以下列格式保存在数据库中:
clob_field_1:1,2,3,4,5,6,7,8,9,10等等......
clob_field_2:8106.23,7856.49,8009.15,8121.78,8082.8,8294.43, 8137.9,8265.81,8319.5,8186.43等等......
理想情况下,结果应如下所示:
[{"项目:" 1,"价值:" 8106.23},{"项目:" 2,"价值:" 7856.49},{"项目:" 3,"价值:" 8009.15},{"项目:" 4,"价值:" 8121.78}等等...]
所以我已经完成了,我已经使用PL / SQL从数据库中获取了clobs文件,因此我可以从JavaScript访问它。之后,我声明了2个变量并设置了对象,并希望循环遍历数据以创建一对漂亮的数据。到目前为止,这是我的JavaScript代码:
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = [8106.23, 7856.49, 8009.15, 8121.78, 8082.8, 8294.43, 8137.9, 8265.81, 8319.5, 8186.43];
var obj = {};
for (var i = 0; i < a.length; i++) {
obj['Item:' + a[i]] = 'Value:' + b[i] + '}';
}
alert(JSON.stringify(obj));
但结果很糟糕,看起来如下:
{"Item:1":"Value:8106.23}","Item:2":"Value:7856.49}","Item:3":"Value:8009.15}","Item:4":"Value:8121.78}","Item:5":"Value:8082.8}","Item:6":"Value:8294.43}","Item:7":"Value:8137.9}","Item:8":"Value:8265.81}","Item:9":"Value:8319.5}","Item:10":"Value:8186.43}"}
左边的花括号从2对开始丢失,冒号而不是昏迷,语音标记位置错误等等...我相信我的代码中有一个syntaxis错误,我无法弄清楚它是什么。任何帮助表示感谢,提前致谢!
答案 0 :(得分:3)
通过map
和ES6语法的紧凑方式:
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = [8106.23, 7856.49, 8009.15, 8121.78, 8082.8, 8294.43, 8137.9, 8265.81,
8319.5, 8186.43];
var obj = a.map( (item, i) => ({ item, value: b[i] }) );
console.log(obj);
&#13;
注意:我建议不要将首字母的属性名称大写。通常只对构造函数执行此操作。
答案 1 :(得分:1)
为输出创建一个数组并将新对象推入其中,而不是将它们全部放在一个对象中。
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = [8106.23, 7856.49, 8009.15, 8121.78, 8082.8, 8294.43, 8137.9, 8265.81, 8319.5, 8186.43];
var output = [];
for (var i = 0; i < a.length; i++) {
output.push({'Item': a[i], 'Value': b[i]});
}
alert(JSON.stringify(output));
答案 2 :(得分:1)
你可以尝试:
var obj = [];
for (var i = 0; i < a.length; i++) {
obj.push({
Item: a[i],
Value: b[i]
});
}
答案 3 :(得分:1)
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = [8106.23, 7856.49, 8009.15, 8121.78, 8082.8, 8294.43, 8137.9, 8265.81, 8319.5, 8186.43];
var objArra = [];
for (var i = 0; i < a.length; i++) {
var obj = {};
obj['Item:'] = a[i];
obj['value:'] = b[i];
objArra.push(obj)
}
alert(JSON.stringify(objArra));
答案 4 :(得分:1)
如果你认为你的输入是正确的,你也可以试试这个
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = [8106.23, 7856.49, 8009.15, 8121.78, 8082.8, 8294.43, 8137.9, 8265.81, 8319.5, 8186.43];
let sum = a.map((val, index) => {
return {'Item':val, 'Value': b[index]};
})