简体   繁体   English

减少无法正常工作?

[英]Reduce not working as expected?

I'm currently trying to convert an array into an object with the array index as the property of the created object. 我目前正在尝试将数组转换为对象,并使用数组索引作为创建对象的属性。

Example Array: ['a','b','c'] 数组示例: ['a','b','c']

Expected Object result: {'1':'a','2':'b','3':'c'} 预期的对象结果: {'1':'a','2':'b','3':'c'}

My code is below, it worked when I used map method but when I use the reduce method instead it comes out weird way: 我的代码在下面,当我使用map方法时有效,但是当我使用reduce方法时,它以奇怪的方式出现:

 let sampleData = ['a','b','c']; let convertArrToObjWithIndexProp = (arr) => { /*let res = {}; arr.map((v,k)=> { res[k+1]=v; }) return res;*/ //--> this outputs {'1':'a','2':'b','3':'c'} return arr.reduce((iv,cv,i)=>{ return Object.assign(iv,iv[i+1]=cv); },{}); //--> this outputs instead {'0':'c','1':'a','2':'b','3':'c'} } console.log(convertArrToObjWithIndexProp(sampleData)); 

Can someone explain to me why its coming out like that? 有人可以向我解释为什么这样出来吗?

Also is using reduce better than using map? 还有使用reduce比使用map更好吗?

The problem is that result of this expression: iv[i+1]=cv is cv , which you then Object.assign to the accumulator. 问题是该表达式的结果: iv[i+1]=cvcv ,然后将Object.assign分配给累加器。 You could make it simpler with a simple assignment: 您可以通过简单的分配使其更简单:

 let sampleData = ['a','b','c']; let convertArrToObjWithIndexProp = (arr) => arr.reduce((iv,cv,i) => (iv[i+1] = cv, iv),{}); console.log(convertArrToObjWithIndexProp(sampleData)); 

Don't use Object.assign . 不要使用Object.assign Just update your object and return it. 只需更新您的对象并返回即可。

 let sampleData = ['a','b','c']; let convertArrToObjWithIndexProp = (arr) => { return arr.reduce((iv,cv,i)=>{ iv[i+1]=cv return iv },{}); } console.log(convertArrToObjWithIndexProp(sampleData)); 

You can achieve it by doing this 您可以通过执行此操作来实现

let array = ['a','b','c'];
return array.reduce((acc, currentValue, index) => {
    const key= index + 1;
    acc[key] = currentValue;
    return acc;
}, {});

Output will be like this 输出将是这样

{
  "1": "a",
  "2": "b",
  "3": "c"
}

 var arr = ['a','b','c']; var result = arr.reduce((obj, val, index) => { obj[index + 1] = val; return obj; }, {}); console.log(result); 

I'd do it with Array.reduce function, and Object computed property. 我可以使用Array.reduce函数和对象计算属性来实现。

 var sampleData = ['a', 'b', 'c']; console.log(sampleData.reduce((mem, curr, index) => ({ ...mem, [index + 1]: curr }), {})) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM