1.匯總數(shù)據(jù)
const customer = [
{id: 1, count: 2},
{id: 2, count: 89},
{id: 3, count: 1}
];
function getSum(total, currentValue, current, arr) {
// total每次返回計(jì)算之后相加的總和,currentValue當(dāng)前的元素台谊,current當(dāng)前的序號,arr當(dāng)前的數(shù)組
debugger;
return total + currentValue.count
}
const totalCount = customer.reduce(getSum, 0) // 表示total的初始值
console.log(totalCount); // 返回計(jì)算的結(jié)果
2.改變數(shù)據(jù)結(jié)構(gòu)
let produts = [
{
id: '123',
name: '蘋果'
},
{
id: '345',
name: '橘子'
}
];
// reduce改變數(shù)據(jù)結(jié)構(gòu)
const produtsById = produts.reduce(
(obj, product) => {
obj[product.id] = product.name
return obj
},
{}
);
console.log('[result]:', produtsById) // {123:'蘋果', 345: '橘子'}
3.對象裝換query字符串
const params = {
color: 'red',
minPrice: 8000,
maxPrice: 10000,
}
const query = '?' + Object.keys(params) // 返回對象key的數(shù)組
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k])).join('&');
console.log(query) // ?color=red&minPrice=8000&maxPrice=10000
- 搜索匹配的數(shù)組元素
const posts = [
{id: 1, title: 'Title 1'},
{id: 2, title: 'Title 2'},
];
const title = posts.find(p => p.id === 1); // 過濾元素(返回對象匹配的第一個元素)
console.log(title)
/*
和filter區(qū)別:
filter返回是數(shù)組宦焦,返回滿足條件的所有元素
find返回的是對象咨堤,返回滿足條件的第一個元素
*/
5.返回匹配的對象數(shù)組元素的index
const posts = [
{id: 1, title: 'Title 1'},
{id: 2, title: 'Title 2'},
{id: 22, title: 'Title 22'}
];
const index = posts.findIndex(p => p.id === 22); // 2
6.刪除某個字段
const user = {
name: 'wuXiaoHui',
age: '25',
password: '19931102',
}
const userWithoutPassword = Object.keys(user) // 返回user里面key的數(shù)組
.filter(key => key !== 'password') // 原數(shù)組篩選調(diào)特定的字段
.map((key, value) => ({[key]: user[key]})) // 每個數(shù)組元素進(jìn)行處理菇篡,返回對象數(shù)組
.reduce((accumulator, current) => ({...accumulator, ...current}), {}); // reduce進(jìn)行對象的拼接
console.log(userWithoutPassword)