如何创建元素并将其推送到多维数组? 我想要实现这样的数组:
var sourceData = [
[0, 99.75], [1, 99.77],
[2, 99.78], [3, 99.84],
[4, 99.82], [5, 99.82],
[6, 99.76], [7, 99.78],
[8, 99.8], [9, 99.65],
[10, 99.94], [11, 99.8]
];
现在,我希望每个子数组中的第一个值像上面那样递增,0,1,2等。应该从json对象中检索子数组右侧的值,例如:
{
"closingbal": "39.00",
"customer_id": "33",
"monthlycashInfow": 658,
"monthlycashOutfow": 674,
"monthyear": "2017-01",
"netcashflow": -16,
"openingbal": "3.00",
"ratioinfoutflow": 0.4286,
"ratioinfoutflowamount": 0.9763,
"transnoInflow": 3,
"transnoOutflow": 7
},
{
"closingbal": "130.00",
"customer_id": "33",
"monthlycashInfow": 4970,
"monthlycashOutfow": 4949,
"monthyear": "2016-12",
"netcashflow": 21,
"openingbal": "19.00",
"ratioinfoutflow": 0.4444,
"ratioinfoutflowamount": 1.0042,
"transnoInflow": 12,
"transnoOutflow": 27
},
{
"closingbal": "1064.00",
"customer_id": "33",
"monthlycashInfow": 3030,
"monthlycashOutfow": 4113,
"monthyear": "2016-11",
"netcashflow": -1083,
"openingbal": "0.00",
"ratioinfoutflow": 0.24,
"ratioinfoutflowamount": 0.7367,
"transnoInflow": 6,
"transnoOutflow": 25
}
我需要在右侧填充“netcashflow”的值。
我怎样才能做到这一点?任何帮助将不胜感激。
这就是我的尝试:
var values = [];
$.each(json, function (key, value) {
if (key == 'cashflows') {
for(var i = 0; i < 12; i++) {
if(!values[i])
values[i] = [];
for(var j = 0; j < json.cashflows.cashflow.length; j++) {
var row = json.cashflows.cashflow[j];
values.push(i+", " +row['netcashflow']);
//values[i].push();
}
}
}
});
答案 0 :(得分:1)
使用Array#map以请求格式创建新数组。传递给Array#map的第二个参数是当前索引,可以用作递增值:
var data = [{"closingbal":"39.00","customer_id":"33","monthlycashInfow":658,"monthlycashOutfow":674,"monthyear":"2017-01","netcashflow":-16,"openingbal":"3.00","ratioinfoutflow":0.4286,"ratioinfoutflowamount":0.9763,"transnoInflow":3,"transnoOutflow":7},{"closingbal":"130.00","customer_id":"33","monthlycashInfow":4970,"monthlycashOutfow":4949,"monthyear":"2016-12","netcashflow":21,"openingbal":"19.00","ratioinfoutflow":0.4444,"ratioinfoutflowamount":1.0042,"transnoInflow":12,"transnoOutflow":27},{"closingbal":"1064.00","customer_id":"33","monthlycashInfow":3030,"monthlycashOutfow":4113,"monthyear":"2016-11","netcashflow":-1083,"openingbal":"0.00","ratioinfoutflow":0.24,"ratioinfoutflowamount":0.7367,"transnoInflow":6,"transnoOutflow":25}];
var sourceData = data.map(function(o, i) {
return [i, o.netcashflow];
});
console.log(sourceData);
答案 1 :(得分:0)
感谢@Ori Dori的方法,我能够像这样实现它:
var data;
var objectStringArray;
$.each(json, function (key, value) {
if (key == 'cashflows') {
data = JSON.stringify(json.cashflows.cashflow);
objectStringArray = (new Function("return " + data+ ";")());
}
});
var sourceData = objectStringArray.map(function(o, i) {
return [i, o.netcashflow];
});