数组方法

1.汇总数据

 const customer = [
{id: 1, count: 2},
{id: 2, count: 89},
{id: 3, count: 1}
];
function getSum(total, currentValue, current, arr) {
    // total每次返回计算之后相加的总和,currentValue当前的元素,current当前的序号,arr当前的数组
    debugger;
    return total + currentValue.count
}
const totalCount = customer.reduce(getSum, 0) // 表示total的初始值
console.log(totalCount); // 返回计算的结果

2.改变数据结构

let produts = [
    {
        id: '123',
        name: '苹果'
    },
    {
        id: '345',
        name: '橘子'
    }
];
  // reduce改变数据结构
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的数组
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k])).join('&');
console.log(query) // ?color=red&minPrice=8000&maxPrice=10000
  1. 搜索匹配的数组元素
 const posts = [
    {id: 1, title: 'Title 1'},
    {id: 2, title: 'Title 2'},
];
const title = posts.find(p => p.id === 1); // 过滤元素(返回对象匹配的第一个元素)
console.log(title)
/*
  和filter区别:
  filter返回是数组,返回满足条件的所有元素
  find返回的是对象,返回满足条件的第一个元素
*/

5.返回匹配的对象数组元素的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的数组
            .filter(key => key !== 'password') // 原数组筛选调特定的字段
            .map((key, value) => ({[key]: user[key]})) // 每个数组元素进行处理,返回对象数组
            .reduce((accumulator, current) => ({...accumulator, ...current}), {}); // reduce进行对象的拼接

            console.log(userWithoutPassword)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容