一.数组
1.去掉数组中undefind
const data = [1, 2, undefined];
const pureData = data.filter(element => element !== undefined);
2.去掉数组中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];
3.数组分类(数组结构变成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’ }]
}
*/
二.对象
1.部分复制对象
const data = {name: ‘伍六七’, age: 12, sex: ‘male’, height: 188};
const {name, age, sex} = data;
const partObj = {name, age, sex}; // {name: “伍六七”, age: 12, sex: “male”}