数组转化为对象,如何把cc=[1,a,2,b,3,c]变为{1:a, 2:b, 3:c}这样的呢

韩知虹
  • 7

js如何把cc=[1,a,2,b,3,c]变为{1:a, 2:b, 3:c}这样的呢

回复
阅读 729
6 个回答
const ret = cc.reduce((acc,curr,i,arr)=>{
    if(i % 2 === 0) acc[curr.toString()] = arr[i + 1]
    return acc
}, {})

console.log(ret)

如果用 lodash 的话,可以这样

Object.fromEntries(_.chunk(cc, 2))
// 纯调整 @SlimBear[lln7777]  代码
data.reduce((obj, item, index, array) => (
    {...obj, ...(index % 2 ? {} : { [item]: array[index + 1]})}
), {})

建议常备lodash

// 将原数组转为二维数组
function transform2Array(arr) {
    var newArr = [], i, j;
    for(i=0, j=-1; i<arr.length; i++) {
        if(i % 2 == 0) {
            j ++;
            newArr[j] = [];
        }
        newArr[j].push(arr[i])
    }
    return newArr;
}

var arr = [1,a,2,b,3,c];
Object.fromEntries(transform2Array(arr))
FengKaiQiang
  • 3
新手上路,请多包涵
const transformArrary = (data) => {
  const newData = {}
  for (let i = 0, leng = data.length / 2; i < leng; i += 1) {
    const key = i * 2
    newData[data[key]] = data[key + 1]
  }
  return newData
}

console.log(transformArrary(cc))
js_coder
  • 2
新手上路,请多包涵
const arrToObj = arr => 
  arr.reduce((obj, item, i) => {
    !(i & 1) && (obj[item] = arr[i + 1])
    return obj
  }, {})
  
const arrToObj1 = arr => {
  let i = 0, target = {}
  for (; i < arr.length; i += 2) target[arr[i]] = arr[i + 1]
  return target
}
你知道吗?

宣传栏