js数据处理小方法
- 二维数字转化为一维数组
1)循环遍历:
let arr1 = [[1,2,3],[12,13,4],[4,5,6]];
let arr2 = [];
arr1.forEach(item => {
item.forEach ? item.forEach(val => {
arr2.push(val)
}) : arr2.push(item)
});
2)用apply的特性:
let arr1 = [[1,2,3],[12,13,4],[4,5,6]];
let arr2 = [].concat.apply([], arr1);
3)利用 es6 的扩展运算符将数组展开:
let arr1 = [[1,2,3],[12,13,4],[4,5,6]];
let arr2 = [].concat(...arr1);
- 多维数字转化为一维数组
1)遍历递归:
let newArr = []; function toOneArray(arr) { for(var i = 0; i< arr.length;i++){ if(Array.isArray(arr[i])){ toOneArray(arr[i]) }else{ newArr.push(arr[i]) } } } let arr1 = [1,[2,[3,[4,[5,6]]]],[23,13]]; let arr2 = [1,[2,[3,[4,[5,6],14],13],12],[23,13]];
2)利用数组转字符串,和字符串转数组的方法:
let arr = [1,[2,[3,[4,[5,6]]]],[23,13]]; let arr1 = arr.toString().split(','); let arr2 = arr.join().split(',');
3)es6的新方法 flat:
注:flat方法默认只是将一层嵌套的数组转化为一位数组,如果不确定有几层嵌套,可以在方法里面传递Infinity,可以这样写arr.flat(Infinity)
let arr = [1,[2,[3,[4,[5,6]]]],[23,13]];
let arr1 = arr.flat(Infinity);
- object转化为数组
1)Object.values 与 Object.keys:
//Object.values()方法返回一个给定对象自身的所有可枚举属性值的数组,值的顺序与使用for...in循环的顺序相同 ( 区别在于 for-in 循环枚举原型链中的属性 )。 let obj = { name: "雨夜看叶", age: 5, skill: "react,vue,taro,react-native" } let arr = Object.values(obj); //对象转化为数组 //注:如果只需要返回键作为数组,可以使用Object.keys()的方式,所以结合//Map,也可以实现: let arr1 = Object.keys(obj).map(function(i){return obj[i]}); //对象转化为数组
let arr2 = Object.keys(obj)
2)循环:
//可以直接利用循环,如for in或者forEach()等: let obj = { name: "雨夜看叶", age: 5, skill: "react,vue,taro,react-native" } let arr = []; //定义数组 for (var i in obj) { arr.push(obj[i]); }
3)Array.from:
//Array.from() 方法对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。 let obj = { name: "雨夜看叶", age: 5, skill: "react,vue,taro,react-native" }
let arr0 = Array.from(obj);
console.log(arr0);// [] 获取的是个空数组 let arr = Array.from(Object.values(obj),x=>x);
//数字为键名的对象获取对象值时的方法展示
let myObj = {0: 'a', 1: 'b', 2: 'c'};
let newObj = {...myObj, ...{length: 3}};
let arr = Array.from(newObj);
let arr1 = Object.values(myObj);//获取键值
let arr2 = Object.keys(myObj);//获取键名
let arr3 = Object.entries(myObj);//转换为数组
console.log(arr); // ["a", "b", "c"]
console.log(arr1);// ["a", "b", "c"]
console.log(arr2);// ["0", "1", "2"]
console.log(arr3);// [["0", "a"], ["1", "b"], ["2", "c"]]
4)Object.entries(object):
//注:返回一个对象自身的键值和数组 let obj = { name: "雨夜看叶", age: 5, skill: "react,vue,taro,react-native" } let arr = Object.entries(obj);
- filter(找指定元素)
let taxonomyLis = [{name: "",value:1},{name: "1",value: 2}]; //数组中对象name值为空的: let data = taxonomyList.filter(function(item){ return item.name == ""; })
- 过滤数组重复元素:
const myArr = [1,1,3,5,7,6,5,2] const set = new Set(myArr) console.log([...set]) //set 有 size 属性。 //set 可以通过 Array.from() 方法转换成数组,或者[...set]