javascript - 此 JavaScript 代码块的更高效但更易读的替代方案
问题描述
假设我有 3 个数组,其中一个基于另一个数组,但我需要将它们组合成一个。我在这里使用 forEach 循环将项目推送到数组,但我觉得这样效率低下。
const arr1 = [1, 2, 3];
const arr2 = ["a", "b"];
const arr3 = ["foo", "bar", "baz"];
const obj = {
"1_a": [1, 2],
"1_b": [1, 2, 3],
"2_a": [1],
"2_b": [1, 2],
"3_a": [],
"3_b": [1, 2, 3]
};
// push all the items to the temporary array - with forEach loops,
// I feel like this logic can be made more readable and efficient
let tempArr = [];
arr1.forEach(i =>
arr2.forEach(j =>
tempArr.push(`${i}_${j}`)
)
);
arr3.forEach(i => tempArr.push(i));
// loop over the temporary array to get the final result (logged below)
const arr = tempArr.map(key => {
if (obj[key] !== undefined && obj[key].length > 1) return `update_${key}`;
else return key;
});
// result
console.log(arr); // [ "update_1_a", "update_1_b", "2_a", "update_2_b", "3_a", "update_3_b" ]
我觉得我在这里的所有推送都做错了forEach
,我觉得应该有类似嵌套地图功能的东西..?请在这里帮我..
我希望发生以下情况:
- arr2 的值基于 arr1 的循环(参见示例),这些值与下划线、伪:组合在一起
arr1Item_arr2Item
,并且该项被推送到数组中。 - arr3 的值,只是被循环和推送
- 合并后的数组被循环,如果该项目的值在对象中,并且该键的数组长于 1,则返回
update_<arrItem>
,否则返回<arrItem>
解决方案
不确定它是否更好,但它是 areduce
和 a map
:
const arr1 = [1, 2, 3];
const arr2 = ["a", "b"];
const arr3 = ["foo", "bar", "baz"];
const obj = {
"1_a": [1, 2],
"1_b": [1, 2, 3],
"2_a": [1],
"2_b": [1, 2],
"3_a": [],
"3_b": [1, 2, 3],
};
const result = arr1.reduce(
(a, c) =>
(a.concat(
arr2.map((y) => {
const key = `${c}_${y}`;
return obj[key] !== undefined && obj[key].length > 1
? `update_${key}`
: key;
})
)),
arr3
);
console.log(result);
推荐阅读
- encryption - 在 collectd 配置中加密密码
- c# - winforms设计器中自定义控件的格式属性
- angular - 如何在 Angular 5 中使用 GET 方法使用 apollo graphql 查询
- php - 如何在使用 PHP 的最后一个斜杠之前获取部分 url?
- scala - 如何在返回数据帧的数据帧列值上映射函数?
- c# - Microsoft Orleans 2.0 颗粒延迟
- bluetooth - UWP 蓝牙通信:bluetoothDevice 对象始终设置为 null
- java - 在没有scenebuilder的javaFX中切换场景
- bosun - Bosun:在通知部分发送认证令牌
- triggers - 在不使用 Future 注释的情况下从触发器中调用