// 原对象 const info = [ { name: "A", value: 4, }, { name: "B", value: 7, }, { name: "C", value: 10, } ]; // 期望对象 { A: 4, B: 7, C: 10, } // reduce: const result = info.reduce((res, cur) => ({...res, [cur.name]: cur.value}), {}); result // {A: 4, B: 7, C: 10}
// 构建一个新数组也是同样的道理,把空数组作为初始值,然后通过迭代向数组中添加元素,最终得到的就是想要的结果数组。 // result为上面得到的{A: 4, B: 7, C: 10} const arrResult = Object.keys(result).reduce((accu, cur) => [...accu, {key: cur, value: result[cur]}], []);
arrResult // [{key: "A", value: 4}, {key: "B", value: 7}, {key: "C", value: 10}]
reduce数组去重
const sample = ["a", "b", "c", "a", "b", "d", "c"];
sample.reduce((acc, cur) => { if (!acc.includes(cur)) { acc.push(cur); } return acc; }, []);
标签:10,cur,reduce,value,构建,result,数组 From: https://www.cnblogs.com/xuhuang/p/17326325.html