使用下划线 _reduce 将数组转换为对象
using underscore _reduce to convert an array to object
如何转换这个数组
var array = ['a', 'b', 'c', 'd', 'a', 'b','c', 'd']
对象
object = { a:2 , b:2, c:2, d:2 }
仅使用 javascript 下划线 _reduce ?
希望对您有所帮助
var array = ['a', 'b', 'c', 'd', 'a', 'b','c', 'd'];
var obj = [...new Set(array)]
.reduce((acc, cur) => ({
...acc,
[cur]: array.filter(item => item === cur).length
}),
{});
console.log(obj);
arr.reduce((obj, currentKey) => {
if(currentKey in obj) {
obj[currentKey] = obk[currentKey] +1
} else{
obj[currentKey] = 1
}
return obj;
}, {});
并对您的代码进行测试,这是输出
如何转换这个数组
var array = ['a', 'b', 'c', 'd', 'a', 'b','c', 'd']
对象
object = { a:2 , b:2, c:2, d:2 }
仅使用 javascript 下划线 _reduce ?
希望对您有所帮助
var array = ['a', 'b', 'c', 'd', 'a', 'b','c', 'd'];
var obj = [...new Set(array)]
.reduce((acc, cur) => ({
...acc,
[cur]: array.filter(item => item === cur).length
}),
{});
console.log(obj);
arr.reduce((obj, currentKey) => {
if(currentKey in obj) {
obj[currentKey] = obk[currentKey] +1
} else{
obj[currentKey] = 1
}
return obj;
}, {});
并对您的代码进行测试,这是输出