Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

以下对象到数组的转换,有没有优雅的方式

const obj = {
    M1:1,
    M2:2,
    M3:3,
    P1:1,
    P2:2,
    P3:2,
    P4:1
}

arr = [
     {name:"M",value:6},
     {name:"P",value:6}
 ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

转换规则没有描述清楚啊,arr 里面 value 6 哪里来的?
obj 里面也没有 6 啊


const arr = Object.entries(obj)
    .reduce((arr, [key, value]) => {
        const index = key.charCodeAt(0)
        if (arr[index]) arr[index] += value
        else arr[index] = value
        return arr
    }, [])
    .map((value, index) => ({
        name: String.fromCharCode(index),
        value
    }))
    .filter(i => i)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...