将对象数组中的多个属性映射到同一个 JavaScript 数组
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/2 16:44:17
假设,我们有一个像这样的对象数组 −
const arr = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6}
];
我们需要编写一个 JavaScript 函数来接收一个这样的对象数组。然后,该函数应将此数组映射到一个数字文字数组,如下所示 −
const output = [1, 2, 3, 4, 5, 6];
示例
const arr = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6}
];
const pushToArray = (arr = []) => {
const result = arr.reduce((acc, obj) => {
acc.push(obj.a);
acc.push(obj.b);
return acc;
}, []);
return result;
};
console.log(pushToArray(arr));
输出
控制台中的输出将是 −
[ 1, 2, 3, 4, 5, 6 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

