js如何把cc=[1,a,2,b,3,c]变为{1:a, 2:b, 3:c}这样的呢
// 纯调整 @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))
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))
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
}
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答5.2k 阅读✓ 已解决
1 回答3.4k 阅读✓ 已解决
3 回答2.5k 阅读✓ 已解决