日常开发中,后端给的数据有时不能直接使用,需要经过一些处理。这里总结一些常用的方法,持续更新。

数组

去掉数组中undefind

const data = [1, 2, undefined];
const pureData = data.filter(element => element !== undefined);

去掉数组中undefind、''、null

const bad = [undefined, '', null];
const data = [1, 2, undefined, null, ''];
const pureData = data.filter(element => !bad.includes(element)); // [1, 2];
// 最简单的写法
const pureData = data.filter(element => element); // [1, 2];

数组分类(数组结构变成map结构)

const animals = [
    {
        "value": 4238,
        "name": "dog"
    },
    {
        "value": 35203,
        "name": "cat"
    },
    {
        "value": 10217,
        "name": "dog"
    },
    {
        "value": 3237,
        "name": "cat"
    }
]

const pureData = animals.reduce(function(sum, curValue) {
    const value = { ...curValue };
    sum[curValue.name] = sum[curValue.name] ? sum[curValue.name].concat(value) : [value];
    return sum;
}, {});
console.log(pureData)
/*
{
    dog:
        [{ value: 4238, name: 'dog' }, { value: 10217, name: 'dog' }],
    cat:
        [{ value: 35203, name: 'cat' }, { value: 3237, name: 'cat' }]
}
*/

对象

部分复制对象

const data = {name: '伍六七', age: 12, sex: 'male', height: 188};
const {name, age, sex} = data;
const partObj = {name, age, sex}; // {name: "伍六七", age: 12, sex: "male"}

seven
6 声望1 粉丝

good good study