我有 2 组嵌套数组:
var values = [[100, 87.5, 87.5, 87.5, 100, 100],
[87.5, 100, 100, 100, 87.5, 87.5],
[75, 75, 75, 75, 75, 75],
[50, 50, 50, 62.5, 62.5, 62.5],
[62.5, 62.5, 62.5, 50, 37.5, 50],
[0, 0, 0, 0, 0, 0]];
var date = [["2015", "2004", "2015", "2015", "2015", "2015"],
["2015", "2004", "2015", "2015", "2015", "2015"],
["2015", "2004", "2015", "2015", "2015", "2015"],
["2015", "2004", "2015", "2015", "2015", "2015"],
["2015", "2004", "2015", "2015", "2015", "2015"],
["2015", "2004", "2015", "2015", "2015", "2015"]];
我想做的是将值和日期中的每个数组组合起来:
Get this :[100, 87.5, 87.5, 87.5, 100, 100]
Get this :["2015", "2004", "2015", "2015", "2015", "2015"]
然后像这样组合:
[{y: 100, d:2015},{y:87.5, d: 2004},{y:87.5, d:2015}},{y:87.5, d:2015}},{y:100, d:2015}},{y:100, d:2015}]
示例:https://jsfiddle.net/zidski/5808pgs4/3/
var result = values.map(function (n, i) {
return ({ y: n, d: values[i] });
});
但是整个数组都被添加了。
最佳答案
您还需要迭代内部数组。
var date = [ ["2015", "2004", "2015", "2015", "2015", "2015"], ["2015", "2004", "2015", "2015", "2015", "2015"], ["2015", "2004", "2015", "2015", "2015", "2015"], ["2015", "2004", "2015", "2015", "2015", "2015"], ["2015", "2004", "2015", "2015", "2015", "2015"], ["2015", "2004", "2015", "2015", "2015", "2015"]];
var values = [ [100, 87.5, 87.5, 87.5, 100, 100], [87.5, 100, 100, 100, 87.5, 87.5], [75, 75, 75, 75, 75, 75], [50, 50, 50, 62.5, 62.5, 62.5], [62.5, 62.5, 62.5, 50, 37.5, 50], [0, 0, 0, 0, 0, 0]];
var result = values
// iterate over the values array
.map(function(arr, i1) {
// iterate over the inner array
// in case you just want the first element as in your example then
// remove the first map method and replace `arr` with `values[0]` and `date[i1][i2]` with `date[0][i2]`
return arr.map(function(n, i2) {
// generate the required array object based on index
return {
y: n,
// get the period from 2d array date using index
periods: date[i1][i2]
}
});
});
document.getElementById("data").innerHTML = JSON.stringify(result, null, 3);
<pre id="data"></pre>
关于javascript - 如何在javascript中组合多个嵌套数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46281762/