替换object对象的键名:
答: JSON.parse(JSON.stringify(data).replace(/keyName/g, ‘name’))
注:data为数组,keyName为修改前的键名,name为修改后的键名
1、JSON.stringify()把json对象转成json字符串;
2、使用正则的replace()方法替换属性名;
3、JSON.parse()把json字符串又转成json对象。
时间匹配:
例: 2021-01-21 11:17:33 正则匹配成只要 2021-01-21 11:17
答: ‘2021-01-21 11:17:33’.replace(/:\d+$/, ‘’)
例: 0:0:15 替换成 0时0分15秒
方法一: '0:0:15'.replace(/(\d+):(\d+):(\d+)/, '$1时$2分$3秒')
方法二: '0:0:15'.split(':').map((x, i) => `${x}${['时', '分', '秒'][i]}`).join('')
年月同理,' 2021-06'..split('-').map((x, i) => `${x}${['年', '月'][i]}`).join('')) //2021年06月
let time= '2021-01-21 11:17:33'
let newTime= `${ time.substring(0,4)} 年${time.substring(5,7)}月` //2021年01月
答: 2021-01-21 11:17:33.substring(0,4)年2021-01-21 11:17:33.substring(5,7)月
原数据:
arr:[
{ month: "2020年5月", date: "06日", name: "分享1:"},
{month: "2020年5月", date: "26日", name: "分享2:"},
{month: "2020年5月", date: "28日", name: "分享3:"},
{month: "2020年4月", date: "06日", name: "分享4:"},
{month: "2020年4月", date: "26日", name: "分享5:"},
{month: "2020年4月", date: "27日", name: "分享6:"}
]
/**处理后的数据
record_arr: [{
month: "2020年5月",
date_arr: [{ date: "06日", name: "分享1:" }, {date: "26日",name: "分享2:"},{date: "28日", name: "分享3:"}]
},
{
month: "2020年4月",
date_arr: [{ date: "06日",name: "分享4:"},{date: "26日",name: "分享5:"}, { date: "28日", name: "分享6:"}]
}
]
//处理返回的数据成二维数组
const groupBy=(list, key = 'id')=> {
if (!list) return [];
const recordMap = new Map();
list.forEach(x => {
if (recordMap.has(x[key])) {
recordMap.set(x[key], [...recordMap.get(x[key]), x]);
} else {
recordMap.set(x[key], [x]);
}
});
return [...recordMap.values()];
},
this.groupBy(beforeData, 'month').map(list => {
//beforeData是你要处理的数组
return {
month: list[0].month,
date_arr: list,
}
})
5 数字转换成数组
// 最简单的方式是先将数字转换成字符串,再分割成数组
//方法一:
let num= 13452
num.toString().split('')
//方法二:
function numberToArray(num) {
const arr = [];
while (num !== 0) {
const digit = num % 10;
num = Math.floor(num / 10);
arr.unshift(digit);
}
return arr;
}
console.log( numberToArray(156)) //[1,5,6]
6 判断电话号码格式是否匹配的正则:
!/^1[3456789]\d{9}$/.test(phone)
//身份证正则
function isIdCard(str) {
return /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(str);
}
//是否为合法域名http https
function isHttpUrl(str) {
return /^(http|https):\/\/[^\s]+$/.test(str);
}
7 时间转换成时间戳
let date = new Date('2021-01-01'); //时间对象,时间须是"xxxx-xx-xx"格式
let str = date.getTime() / 1000; //转换成时间戳 ,getTime()会精确到毫秒,所以需要除以1000,再传给后端
console.log(str,"时间戳-------")
8 时间戳转时间
//方法一: (可能出现有些浏览器格式不相同问题,用uniapp小程序开发者工具预览和手机预览出现不同显示方式)
let date= new Date(1609430400);//直接用 new Date(时间戳) 格式转化获得当前时间
console.log(date);
console.log(date.toLocaleDateString().replace(/\//g, "-") + " " + date.toTimeString().substr(0, 8)); //再利用拼接正则等手段转化为yyyy-MM-dd hh:mm:ss 格式
//方法二
getdate(time, type) {
//time参数:时间戳
let now = new Date(time),
y = now.getFullYear(),
m = now.getMonth() + 1,
d = now.getDate();
if (type === 'birthday') {
return `${y}-${(m < 10 ? "0" + m : m)}-${(d < 10 ? "0" + d : d)}`
//返回的是 'yyyy-mm-dd' 格式
} else {
//返回的是 'yyyy-mm-dd hh-ss' 格式
return `${y}-${(m < 10 ? "0" + m : m)}-${(d < 10 ? "0" + d : d)} ${ now.toTimeString().substr(0, 5)}`
}
},
9 电话号码加密,中间四位加星号
"19919203800".replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
10 获取字符串中的参数值
在做项目时,可能会遇见值为"storeid%3D1%26tablesid%3D1%26type%3D1"这种,url通过UTF-8编码的转义后的值,首先url要解析成正常字符串,然后再获取参数值
let str="storeid%3D1%26tablesid%3D1%26type%3D1"
let newStr=decodeURIComponent(str) //解析成正常字符串
console.log(newStr) // storeid=1&tablesid=1&type=1
//方法一:
let obj=newStr.reduce( (res, keyvalue) => {
const [key, value] = keyvalue.split('=')
return {
...res,
[key]: value
}
}, {} )
console.log(obj) // {storeid: "1", tablesid: "1", type: "1"} 这样我们就拿到对象值啦
// 方法二: 通过API URLSearchParams
URLSearchParams
11 二维数组,根据数据内部的某条数据来进行分类,外层数据不重复
//源数据
goods=[
{
title:"短发",
goods:[{sex:0,name:'短发一'},{sex:1,name:'短发二'},{sex:1,name:'短发三'}]
},
{title:"中长发"},
{
title:"长发",
goods:[{sex:0,name:长发一'},{sex:1,name:'长发二'},{sex:1,name:'长发三'}]
},
]
//处理后的数据
manList=[
{title:'短发',goods:[{sex:0,name:'短发一'},]},
{title:'长发',goods:[{sex:0,name:长发一'},]},
]
womanList:=[
{title:'短发',goods:[{sex:1,name:'短发二'},{sex:1,name:'短发三'}]},
{title:'长发',goods:[{sex:1,name:'长发二'},{sex:1,name:'长发三'}]},
]
const isEmptyArray = x => !(Array.isArray(x) && x.length > 0) //判断数据是否为空
const deepClone = x => JSON.parse(JSON.stringify(x)); //深克隆数据
const getSexGoods = (classify) => {
const m = [];
const wm = [];
classify.goods.forEach(good => (String(good.sex) === '0' ? m : wm).push(good));
return [{
...deepClone(classify),
goods: m,
}, {
...deepClone(classify),
goods: wm,
}];
};
const [manList, womanList] = data.goods.reduce(([m, wm], classify) => {
if (!classify.goods) return [m, wm]; //跳过没有goods的数据
const [mItem, wmItem] = getSexGoods(classify)
return [
m.concat(isEmptyArray(mItem.goods) ? [] : mItem),
wm.concat(isEmptyArray(wmItem.goods) ? [] : wmItem),
]
}, [[], []]);
console.log({manList, womanList})
12 js获取页面url,获取想要的参数值
const url = window.location.href;// 获取当前页面的url
例:url='https://www.service_muban/edit?id=21&ref=addtabs'
getQueryData(arg) {
let query = window.location.search.substring(1);//获取当前url的参数值,就是?后面的传参
let vars = query.split("&");
for (let i = 0; i < vars.length; i++) {
let arr= vars[i].split("=");
if (arr[0] === arg) {
return arr[1];
}
}
return false;
},
let id= this.getQueryData("id"); //21
13 字符串拼接,前面加特殊符号,第一位不添加
str = str=== ' ' ? str + item.name : str + ' , ' + item.name
14 获取对象下某个键的键值
const objs={'name':'张三',''age': 24}
console.log(objs[Object.keys(objs)[0]]) //'张三'
15 字符串转obj
当后端返回数据有时成了字符串,我们可以这样转换
方法1:
res={errMsg: 'uploadFile:ok', statusCode: 200, data: '{"code":1,"msg":"上传成功","time":"1649390547","data":…20220408\\/2bc2e0ac4f89cea7f0c88dc40642e253.jpg"}}'}
eval('('+res.data+')')
方法二:
JSON.parse(res.data)