js配列オブジェクトのデフラグ
3296 ワード
var arr = [{
key: '01',
value: ' '
}, {
key: '02',
value: ' '
}, {
key: '03',
value: ' '
},{
key: '04',
value: ' '
},{
key: '01',
value: ' '
}];
// 1: , key
var result = [];
var obj = {};
for(var i =0; i){
if(!obj[arr[i].key]){
result.push(arr[i]);
obj[arr[i].key] = true;
}
}
const result = []
const obj = {}
for (let i = 0; i < data.length; i++) {
if (!obj[data[i].key]) {
result.push(data[i])
obj[data[i].key] = true
}
}
console.log('result ', result)
console.log(result); // [{key: "01", value: " "},{key: "02", value: " "},{key: "03", value: " "},{key: "04", value: " "}]
// 2: reduce ,reduce , item
var obj = {};
arr = arr.reduce(function(item, next) {
obj[next.key] ? '' : obj[next.key] = true && item.push(next);
return item;
}, []);
console.log(arr); // [{key: "01", value: " "},{key: "02", value: " "},{key: "03", value: " "},{key: "04", value: " "}]