前端常用的数据处理(基础版)

1、字符串、数组互转

//字符串转数组
let str = '一公司,二公司,三公司';
console.log(str.split(',')); //['一公司,二公司,三公司']
// console.log(Array.from(str));
// console.log([...str]);

  

//数组转字符串
let strArr = ['一公司','二公司','三公司'];
console.log(strArr.join());//一公司,二公司,三公司
// console.log(strArr.toString());

  

2、数组、对象互转

//数组转对象
const arr = [
  { label: '男', value: 0 },
  { label: '女', value: 1 }
];
const arrObj = {};
for(let i = 0; i < arr.length; i++) {
   arrObj[arr[i].value] = arr[i].label;
}
console.log(arrObj);
//{0: '男', 1: '女'}

  

//对象转数组
const obj = { 0: '男', 1: '女' };
let objArr = [];
for (let key in obj) {
   objArr.push({ label: obj[key], value: +key })
}
console.log(objArr);

  

 

3、数组合并、对象合并

//数组合并
let m1 = ['js', 'es', 'ts'], m2 = ['vue','react'];
let mergeM = m1.concat(m2);
console.log(mergeM);
//['js', 'es', 'ts', 'vue', 'react']

  

//对象合并
let o1 = { a: 1, b: 2 }, o2 = { c: 3, d: 4 };
let mergeO = Object.assign(o1, o2);
console.log(mergeO);
//{a: 1, b: 2, c: 3, d: 4}

  

 4、判断是否是空数组、空对象

//判断是否是空数组
let a1 = [], a2 = [1,2,3];
function isArray(arr) {
     if (arr instanceof Array && arr.length === 0) return true;
     return false;
}
console.log(isArray(a1));//true
console.log(isArray(a2));//false

  

//判断是否是空对象-利用hasOwnProperty
let u1 = {}, u2 = { p:9 };
function isObject(obj) {
     for(let key in obj) {
        //如果有key属性代表不是一个空对象,返回false
	if (obj.hasOwnProperty(key)) return false;
     }
     return true;
}
console.log(isObject(u1));//true
console.log(isObject(u2));//false

//判断是否是空对象-利用Object.keys
function isObject2(obj) {
     if (Object.keys(obj).length === 0) return true;
     return false;
}
console.log(isObject2(u1));//true
console.log(isObject2(u2));//false

  

 5、将时间戳转成日期格式

function getExactTime(time) {
	//时间戳为10位需*1000,时间戳为13位的话不需乘1000
	// var date = new Date(time);
	var date = new Date(time * 1000);
	var year = date.getFullYear() + '年';
	var month =  (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
	var day = date.getHours() + '日';
	var hour = date.getDate() + '时';
	var min = date.getMinutes() + '分';
	var second = date.getSeconds() + '秒';
	return year + month + day + hour + min + second;
}
console.log(getExactTime(1651373079));
//2022年05月10日1时44分39秒

  

6、数组去重

//第一种
let fiveNumber = [1,2,3,3,2,1,1,2,3,4,5,6,7];
function unique1(fiveNumber) {
	let s = new Set(fiveNumber);
	return Array.from(s);
}
function unique2(fiveNumber){
  return fiveNumber.reduce((pre, cur) => {
  	return pre.includes(cur) ? pre : pre.concat(cur);
  }, [])
}
console.log(unique1(fiveNumber));
console.log(unique2(fiveNumber));
//[1, 2, 3, 4, 5, 6, 7]

//第二种
const jordan = [
	{ goodsId: '1', user: 'jack', uniId: 20 },
	{ goodsId: '2', user: 'tom', uniId: 20 },
	{ goodsId: '1', user: 'jack', uniId: 20 },
	{ goodsId: '3', user: 'rose', uniId: 20 },
	{ goodsId: '1', user: 'jack', uniId: 20 },
]
function uniqueJordan(jordan) {
	let obj = {};
	return jordan.reduce((pre, cur) => {
		obj[cur.goodsId]  ? '' : obj[cur.goodsId] = true && pre.push(cur);
		return pre;
	}, [])
}
console.log(uniqueJordan(jordan))

  

 

7、数组扁平化

let six = [1, [2, [3, 4]],[5,6],[7]];
function flatten(six) {
	return six.reduce((pre, cur) => {
		return pre.concat(Array.isArray(cur) ? flatten(cur) : cur);
	}, [])
}
console.log(flatten(six));
//[1, 2, 3, 4, 5, 6, 7]

  

8、数字千分位格式化

let n = '1234567';
function formatNum(n) {
	return n.split('').reverse().reduce((cur, next, index) => {
		//看index是否能被3整除
		return ((index % 3) ? next : (next + ',')) + cur
	})
}
console.log(formatNum(n));//1,234,567

  

 9、url参数转对象

let query = 'http://www.bd.com/?user=rose&id=123&pid=01&city=beijing';
function getQueryParams(query) {
    /*
    ?user=rose&id=123&pid=01&city=beijing
    [?&]        带有?和&的
    [^?&]+=     非问号&号的(多个)和等号
    */
    const result = {};
    const reg = /[?&][^?&]+=[^?&]+/g;
    const found = query.match(reg);
    if (found) {
        found.forEach(item => {
            let temp = item.substring(1).split('=');
            console.log(temp, 'LOG')
            let key = temp[0], val = temp[1];
            result[key] = val;
        })
    }
    return result;
}
console.log(getQueryParams(query));
//{user: 'rose', id: '123', pid: '01', city: 'beijing'}

  

  

10、一维数组转树形结构

let data = [
	{ id: 1, parent: null, text: '菜单1' },
	{ id: 11, parent: 1, text: '菜单1-1' },
	{ id: 12, parent: 1, text: '菜单1-2' },
	{ id: 2, parent: null, text: '菜单2' },
	{ id: 21, parent: 2, text: '菜单2-1' },
	{ id: 22, parent: 2, text: '菜单2-2' }
]
function jsonTree(data, p, list) {
	for (let item of data) {
		if (item.parent == p) list.push(item);
	}
	console.log(list, '-----')
	for (let i of list) {
		i.children = [];
		//递归
		jsonTree(data, i.id, i.children);
		if(i.children.length == 0) delete i.children;
	}
	return list;
}
//调用的三个参数分别为源数据、父级节点的标识、默认[]
//jsonTree(data, null, []);
console.log(jsonTree(data, null, []));

 

 

posted @ 2022-05-02 16:34  紫诺花开  阅读(481)  评论(0编辑  收藏  举报