JavaScript 如何在另一个对象数组中传递数组
在本文中,我们将通过具体示例来了解如何在JavaScript中将一个数组传递给另一个对象数组。
先决条件: JavaScript中的对象数组
示例:
Input:
[
[
[100, 100, 100],
[100, 100, 98, 50],
[100, 100, 100, 20],
],
[
[100, 100, 100, 99],
[100, 100, 100, 100],
],
]
Output:
[
[{ total: 300 }, { total: 348 }, { total: 320 }],
[{ total: 399 }, { total: 400 }]
]
以下是将一个数组传递给另一个对象数组的方法:
- 使用forEach()循环
- 使用map()和reduce()方法
方法1:使用forEach()循环
- 创建一个临时数组result变量
- 使用forEach()循环遍历数组,并在其中创建另一个临时数组来存储值,并使用这些内部值计算每个对应行的某些值,然后将它们作为另一个对象添加
- 将对象数组显示为输出
示例: 在这个例子中,我们首先需要遍历数组的数组,然后对于每个数组的值,我们需要计算每个数组对应行的总和。
Javascript
let numbers_array = [
[
[100, 100, 100],
[100, 100, 98, 50],
[100, 100, 100, 20],
],
[
[100, 100, 100, 99],
[100, 100, 100, 100],
],
];
let desired_output = (numbers_array) => {
let result = [];
numbers_array.forEach((element) => {
let sumCalc = [];
element.forEach((item) => {
let sum = 0;
item.map((value) => {
sum += value;
});
sumCalc.push({ total: sum });
});
result.push(sumCalc);
});
return result;
};
console.log(desired_output(numbers_array));
输出
[
[ { total: 300 }, { total: 348 }, { total: 320 } ],
[ { total: 399 }, { total: 400 } ]
]
方法2:使用 map() 和 reduce() 方法
- 在这种方法中,我们将使用 map() 方法来遍历主数组。
- 然后,我们使用 reduce() 方法将值减少为输出本身的总和。
- 然后,我们将总和值作为键值对推入对象中,稍后将返回该对象。
示例: 下面是上述方法的实现。
Javascript
let numbers_array = [
[
[100, 100, 100],
[100, 100, 98, 50],
[100, 100, 100, 20],
],
[
[100, 100, 100, 99],
[100, 100, 100, 100],
],
];
let desired_output = (numbers_array) => {
let data = numbers_array.map((item) =>
item.map((row) => {
let total_value = row.reduce(
(previous_value, current_value) =>
previous_value + current_value,
0
);
return { total: total_value };
})
);
return data;
};
console.log(desired_output(numbers_array));
输出
[
[ { total: 300 }, { total: 348 }, { total: 320 } ],
[ { total: 399 }, { total: 400 } ]
]
方法3:使用展开运算符
展开运算符 允许在期望接受0个或多个参数的位置上扩展一个可迭代对象。它主要用于变量数组中,需要多个值的情况下。它让我们有特权从数组中获取一系列参数。
示例:
JavaScript
const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];
const newArray = [
{ id: 1, name: 'Object 1', values: [...arr1] },
{ id: 2, name: 'Object 2', values: [...arr2] }
];
console.log(newArray);
输出
[
{ id: 1, name: 'Object 1', values: [ 1, 2, 3 ] },
{ id: 2, name: 'Object 2', values: [ 'a', 'b', 'c' ] }
]
极客教程