如何用一行代码将指定数组转换为目标对象?
数组转目标对象的一行代码实现
这里提供两种符合要求的一行代码实现方式:
方式一:使用reduce方法
const arr = [{type: 'fruit', value: 'apple'}, {type: 'meat', value: 'pig'}, {type: 'vegetable', value: 'carrot'}, {type: 'desert', value: 'cake'}]; const targetObj = arr.reduce((acc, { value }) => ({ ...acc, [value]: true }), {});
通过reduce遍历原数组,每次解构出元素的value属性,利用对象扩展运算符将累加对象与当前value: true的键值对合并,初始累加值设为空对象,最终得到目标结构。
方式二:使用Object.fromEntries结合map
const arr = [{type: 'fruit', value: 'apple'}, {type: 'meat', value: 'pig'}, {type: 'vegetable', value: 'carrot'}, {type: 'desert', value: 'cake'}]; const targetObj = Object.fromEntries(arr.map(item => [item.value, true]));
先通过map将原数组的每个元素转换为[value, true]格式的键值对数组,再用Object.fromEntries将这个二维数组直接转换为目标对象,代码更简洁直观。
内容的提问来源于stack exchange,提问作者formal
相关产品推荐
相关产品推荐

