小题目 (数组转化为对象)

110 阅读1分钟

小题目

const arr = [{ label: 'man', value: 1 }, { label: 'woman', value: 0 }]
function f (arr) {
  ...
}
const obj = f(arr)
console.log(obj)
// 使输出obj为{ 0: 'men', 1: 'women' }

第一种思路 (forEach循环)

const arr = [{ label: 'men', value: 1 }, { label: 'women', value: 0 }]
function f (arr) {
  let obj = {}
  arr.forEach(item => {
    obj[item.value] = item.label
  })
  return obj
}
const obj = f(arr)
console.log(obj)

image.png

第二种思路 (使用reduce)

const arr = [{ label: 'men', value: 1 }, { label: 'women', value: 0 }]
function f (arr) {
  return arr.reduce((result, item) => {
    return { ...result, [item.value]: item.label }
  }, {})
}
const obj = f(arr)
console.log(obj)

image.png

第三种思路


  ...

还需要更加理解透彻