我有一个像这样的JSON对象
var test = {
"value1": "",
"array1": {
"value2": 0,
"value3": 0
}
}
现在我想在测试JSON中迭代array1并将值相乘并再次存储它们......
我试过这种方式,但它没有存储它
jQuery.each(test.array1, function (i, val) {
test.array1.i = val * 1.3;
});
乘法工作正常..但如何正确恢复呢?
答案 0 :(得分:3)
您可以在密钥数组上使用Array#forEach
,使用Object.keys()
。
Object.keys(test.array1).forEach(function(key) {
test.array1[key] *= 1.3;
});
Object.keys(test.array1).forEach(key => test.array1[key] *= 1.3);
var test = {
"value1": "",
"array1": {
"value2": 10,
"value3": 30
}
};
Object.keys(test.array1).forEach(function(key) {
test.array1[key] *= 1.3;
});
console.log(test);

答案 1 :(得分:2)
使用test.array1[i]
代替test.array1.i
,如下所示。
jQuery.each(test.array1, function (i, val) {
test.array1[i] = val * 1.3;
});
答案 2 :(得分:2)
这样做:
var test = {
"value1": "",
"array1": {
"value2": 1,
"value3": 0
}
}
jQuery.each(test.array1, function (i, val) {
console.log(i, val)
test.array1[i] = val * 1.3;//instead of test.array1.i = val * 1.3; use the bracket notation
});
console.log(test)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 3 :(得分:2)
没有jQuery,就可以这样做:
var test = {
"value1": "",
"array1": {
"value2": 1,
"value3": 2
}
}
for (key in test.array1) {
test.array1[key] *= 1.3;
}
console.log(test);
运行代码段以检查其工作原理。