数据处理数据技巧

174 阅读1分钟

使用reduce将数组转换为对象

reduce((m, x) => m.set(x, (m.get(x) || 0) + 1), new Map())
demo:
[1, 2, 3, 4, 5, 6, 7, 7, 3, 4].reduce((m, x) => m.set(x, (m.get(x) || 0) + 1), new Map())
 
0: { 1 => 1 }
1: { 2 => 1 }
2: { 3 => 2 }
3: { 4 => 2 }
4: { 5 => 1 }
5: { 6 => 1 }
6: { 7 => 2 }

使用new Set对数据去重

[...new Set(arr)]
demo:
[...new Set([1, 2, 3, 4, 5, 6, 2, 1, 2, 3, 4])]
 
0: 1
1: 2
2: 3
3: 4
4: 5
5: 6

使用reduce将数组转换为对象

demo:
let list = [{
    usertype: 'front',
    user: 'marcotian'
},
{
    usertype: 'back',
    user: 'jeremieastrayye'
}]
 
 
let arr = list.reduce((obj, item) => {
    return Object.assign({}, obj, {
        [item.user]: item.usertype
    })
}, {})
 
{
    jeremieastrayye: "back"
    marcotian: "front"
}

使用Array.from将类数组对象转换为数组

let arrayLike = {
    0: 'tom',
    1: '65',
    2: '男',
    3: ['jane', 'john', 'Mary'],
    'length': 4
}
let arr = Array.from(arrayLike)
console.log(arr) // ['tom','65','男',['jane','john','Mary']]