的javascript
我正在尝试在同一索引处合并2个多维数组,或者将两个数组的相同索引随机化。
var arr1 = [[a, b, c], [d, e], [f, g, h, i]]
var arr2 = [[1, 2, 3], [5, 6], [7, 8, 9, 10]]
preferredResult = [{a: 1, b: 2, c: 3}, {d: 5, e:6}, {f: 7, g: 8, h: 9, i: 10}]
我尝试过.maps,嵌套for循环,.push在不同的版本中,并且无法解决这个问题。
或者,如果我能弄清楚如何以相同的方式随机化两个数组数组,那也可以,即:arr1 [0]中的字母和arr2 [0]中的数字可以设置为相同的随机化,然后是arr1 [1]& arr2 [1]等等。
答案 0 :(得分:0)
function merge(arr1, arr2) {
return arr1.map(function (arr, i) {
return mergeIntoObject(arr1[i], arr2[i]));
};
}
function mergeIntoObject(arr1, arr2) {
var result = {};
arr1.forEach((arr, i) => {
result[arr1[i]] = arr2[i];
});
return result;
}
merge(arr1, arr2);
答案 1 :(得分:0)
使用嵌入式for
循环
var arr1 = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']]
var arr2 = [[1, 2, 3], [5, 6], [7, 8, 9, 10]]
var result = []
for (let i = 0; i < arr1.length; i++){
let obj = {};
for (let j = 0; j < arr1[i].length; j++){
obj[arr1[i][j]]=arr2[i][j]
}
result.push(obj);
}
console.log(result)
&#13;
答案 2 :(得分:0)
您可以使用array#map
和array#reduce
const arr1 = [['a', 'b', 'c'], ['d','e' ], ['f', 'g', 'h', 'i']],
arr2 = [[1, 2, 3], [5, 6], [7, 8, 9, 10]],
result = arr1.map(function(a, i){
return a.reduce(function(r, v, j){
r[v] = arr2[i][j];
return r;
}, {});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 3 :(得分:0)
Lodash可以提供超级帮助。
var arr1 = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']]
var arr2 = [[1, 2, 3], [5, 6], [7, 8, 9, 10]]
var out = _.zipWith(arr1, arr2, (x,y)=>_.fromPairs(_.zip(x,y)));
console.log(out)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
zip将两个数组合并成一对,zipWith也会这样做,但是让你选择如何组合它们。
答案 4 :(得分:0)
使用public final class ImmutableButton {
public final String text;
public ImmutableButton(String text) {
this.text = text;
}
protected void onClick() {
// notify listeners somehow, hoping they haven't changed
}
}
public final class ImmutableWindow {
public final ImmutableButton button;
public ImmutableWindow(ImmutableButton button) {
this.button = button;
}
protected void listenForButtonClick() {
// somehow register with button and receive events, despite this object
// being entirely recreated whenever a field changes
}
}
&amp; map
方法
forEach