js 陣列物件去重
阿新 • • 發佈:2018-12-12
let hash = {}; let config = [ { name: 2, state: true, output: 'Y'}, { name: 3, state: true, output: 'A'}, { name: 5, state: true, output: 'S'}, { name: 7, state: true, output: 'B'} ]; config = [...config, { // 合併陣列 ...運算子即為陣列展開運算子 name: 3, state:false, output: 'A', }] const newArr = config.reduce((item, next) => { console.log('hash--',hash) console.log('next--',next.name) console.log('hash[next.name]--',hash[next.name]) hash[next.name] ? '' : hash[next.name] = true && item.push(next);return item }, []); //[{"name":2,"state":true,"output":"Y"},{"name":3,"state":true,"output":"A"},{"name":5,"state":true,"output":"S"},{"name":7,"state":true,"output":"B"}]