关于es6一些应用 和 其他对前后台数据的处理
文章目录
- 关于es6一些应用 和 其他对前后台数据的处理
- 一、给数组里的对象添加一个属性
- 二、下拉选择得到id 获取其他属性
- 三、属性替换
- 四、遍历数组为【1,2,3,4】
- 五、根据条件过滤数组
- 六、树形结构设置disabled属性
- 七、遍历数组 修改属性值
- 八、遍历数组 添加属性值
- 九、数组A有数组B的数据就删除
- 十、es6 两个数组取相同项和不同项
- 十一、实现从json中取值并返回新的数组或者字符串
- 十二、删除对象或数组中的某个属性
- 十四、大小写转换
- 十五、对象数组去重
- 十六、数组里某个字段排顺序
- 十七、数组里的数组添加新属性
- 十八、解析headers里content-disposition文件名称
- 十九、查找选中数值下标
- 二十、es6两个数组比较如果某字段相同,给一个字段赋值
- 二十一、数组里的字符串数字与数字互转
- 二十二、350000转成350,000
- 二十三、数据转为以万为单位
- 二十四、需要用A接口得参数去请求B接口
- 二十五、es6去重
- 二十六、es6去数组中的值作为对象里的键
- 二十七、字符串转数组,数组转字符串
- 二十八、字符串转数组数字
- 二十九、数组对象里的值累加
- 三十、350000转成350,000.00
- 三十一、实现并集、交集和差集
- 三十二、数组扁平化处理
- 三十三、对象里的健和值,组成一个新数组
一、给数组里的对象添加一个属性
this.data.forEach((item,index)=>{
needData.push(
Object.assign({},item,
{'addAttr':'addAttrContent'})
)
})
二、下拉选择得到id 获取其他属性
let currentItemSkuUnit = {};
currentItemSkuUnit = this.specKeyData.find((item) => {
return item.id === value;
});
this.detailForm.specRatio = currentItemSkuUnit.specRatio;
三、属性替换
this.addFormDataOne = JSON.parse(JSON.stringify(this.addFormDataOne).replace(/cusAddress/g, 'address'))
四、遍历数组为【1,2,3,4】
this.detailForm.areas = [];
this.categoryData.map((item) => {
this.detailForm.areas.push(item.whAId);
});
五、根据条件过滤数组
this.detailForm.owners = this.detailForm.owners.filter((item) => {
return item !== "null";
});
六、树形结构设置disabled属性
tickMenuIdFilter(arr, data) {
var newArr = [];
if (arr != undefined && arr.length > 0) {
newArr = arr.map((item) => {
item.disabled = data;
if (item.areaList != undefined && item.areaList.length > 0) {
this.tickMenuIdFilter(item.areaList, data);
}
return item;
});
}
console.log(newArr);
return newArr;
},
this.tickMenuIdFilter(this.popupTreeData, true)
七、遍历数组 修改属性值
data.forEach((item) => {
if (item.whState == 0) {
item.whState = false;
} else {
item.whState = true;
}
return data;
});
this.popupTreeData = data;
八、遍历数组 添加属性值
var arr = [];
this.adjustType.forEach((item, index) => {
if (item.id !== row.state) {
arr.push(Object.assign({}, item, { disabled: true }));
this.adjustType = arr;
}
});
九、数组A有数组B的数据就删除
arrayWeightRemoval(array1, array2) {
//临时数组存放
var tempArray1 = []; //临时数组1
var tempArray2 = []; //临时数组2
for (var i = 0; i < array2.length; i++) {
tempArray1[array2[i]] = true; //将数array2 中的元素值作为tempArray1 中的键,值为true;
}
for (var i = 0; i < array1.length; i++) {
if (!tempArray1[array1[i]]) {
tempArray2.push(array1[i]); //过滤array1 中与array2 相同的元素;
}
}
return tempArray2;
}
十、es6 两个数组取相同项和不同项
//相同
let arr = [{ id: 1, name: 'zs' }, { id: 2, name: 'ls' }, { id: 3, name: 'ww' }, { id: 4, name: 'xm' }, { id: 5, name: 'xh' },]
let sum = [3, 4, 5]
let date = arr.filter(item => sum.indexOf(item.id) > -1)
console.log('date', date)
// 0: {id: 3, name: "ww"}
// 1: {id: 4, name: "xm"}
// 2: {id: 5, name: "xh"}
//相同
let arr = [{ id: 1, name: 'zs' }, { id: 2, name: 'ls' }, { id: 3, name: 'ww' }, { id: 4, name: 'xm' }, { id: 5, name: 'xh' },]
let arr2 = [{ id: 1, name: 'zs' }]
let newArr = arr.filter((item) =>
arr2.some((ele) => ele.id === item.id)
);
console.log('newArr', newArr )
//不同
let arr = [{ id: 1, name: 'zs' }, { id: 2, name: 'ls' }, { id: 3, name: 'ww' }, { id: 4, name: 'xm' }, { id: 5, name: 'xh' },]
let arr2 = [{ id: 1, name: 'zs' }]
let newArr = arr.filter((item) =>
!arr2.some((ele) => ele.id === item.id)
);
console.log('newArr', newArr )
十一、实现从json中取值并返回新的数组或者字符串
data:[
{
'Id': '1',
'Phone': '123456',
'Name': '张三',
},
{
'Id': '2',
'Phone': '78945',
'Name': '李四',
},
{
'Id': '3',
'Phone': '123789',
'Name': '王五',
}
]
//data json的名称,n是自定义取的
let result = data.map(n=> n.name).join();//'张三,李四,王五'
let results = data.map(n => n.name);//['张三','李四','王五']
十二、删除对象或数组中的某个属性
1.删除对象中的某个属性
let { createTime, ...params } = data;
console.log(params)
最后这个params就是我们需要的值
2.删除数组中的某个属性
var arrayData = [
{
index: 0,
is_required: true,
name: "vmvdnksl",
type: "LONG_TEXT",
},
{
index: 1,
is_required: true,
name: "dsvnlk",
type: "MULTIPLE_SELECTORS",
},
];
for (let key in arrayData) {
delete arrayData[key].index;
}
```
# 十三、过滤组数中null 空字符串 undefined
```javascript
var arr = ['1','2',undefined, '3.jpg',undefined]
var newArr = arr.filter(item => item)
console.log(newArr)
var arr = ['1','2',null, '3.jpg',null]
var newArr = arr.filter(item => item)
console.log(newArr)
>//空字符串里面不能包含空格
var arr = ['1','2','', '3.jpg','']
var newArr = arr.filter(item => item)
console.log(newArr)
十四、大小写转换
// 大写转换
function upperJSONKey(jsonObj){
for (var key in jsonObj){
jsonObj["\""+key.toUpperCase()+"\""] = jsonObj[key];
delete(jsonObj[key]);
}
return jsonObj;
}
// 小写转换
function lowerJSONKey(jsonObj){
for (var key in jsonObj){
jsonObj["\""+key.toLowerCase()+"\""] = jsonObj[key];
delete(jsonObj[key]);
}
return jsonObj;
}
var obj = {KEY:'value'};
var newObj = lowerJSONKey(obj);
console.log(newObj);
十五、对象数组去重
const arr = [
{
name: '张三',
age: 22
},
{
name: '李四',
age: 22
},
{
name: '张三',
age: 23
}
]
const map = new Map()
const qc = arr.filter(key => !map.has(key.name) && map.set(key.name, 1)) // 这里对name属性进行去重
console.log('qc')
console.log(qc)
十六、数组里某个字段排顺序
var detailsData = res.data.data.details;
detailsData.sort((old, New) => {
return old.diffNum - New.diffNum;
});
十七、数组里的数组添加新属性
this.detailList = res.data.data;
this.detailList.forEach((item, index) => {
if (item.allocateResult) {
var ResultData = [];
item.allocateResult.forEach((key) => {
ResultData.push(
Object.assign(key, {
inventoryOutStateTwo: item.inventoryOutState,
})
);
});
item.allocateResult = ResultData;
console.log(item.allocateResult);
十八、解析headers里content-disposition文件名称
let filename = decodeURIComponent(
res.headers["content-disposition"].split("filename=")[1]
);
link.setAttribute("download", filename);
十九、查找选中数值下标
changeZcodeEnd(value) {
const ZcodeData = ['a','b','c'];
const One = ZcodeData.findIndex((item) => {
return item == value;
});
console.log(One)
}
二十、es6两个数组比较如果某字段相同,给一个字段赋值
this.tableHeadsSon.filter((item) => {
tableHeadsData.find((key) => {
if (item.prop == key.prop) {
return (item.width = key.width);
}
});
});
二十一、数组里的字符串数字与数字互转
var arr = [1, 2, 3, 4, 5];
arr.map(String); // ['1', '2', '3', '4', '5']
var arr2 = ['1', '2', '3', '4', '5']
arr2.map(Number); //[1, 2, 3, 4, 5]
二十二、350000转成350,000
new Intl.NumberFormat().format(350000)
二十三、数据转为以万为单位
//转换单位万
export function formatNumber(num) {
num = Number(num);
if (num == 0) {
return num + '';
} else if (num > 0 && num < 10000) {
return parseFloat((num).toFixed(2)) + '';
} else {
return (num / 10000).toFixed(2) + '万';
}
}
二十四、需要用A接口得参数去请求B接口
Promise.all([
new Promise((resolve, reject) => {
//请求A接口,这里用setTimeout模拟请求
setTimeout(() => {
resolve("A的结果");
}, 2000);
}),
new Promise((resolve, reject) => {
//请求B接口,这里用setTimeout模拟请求
setTimeout(() => {
resolve("B的结果");
}, 1000);
}),
])
.then((res) => {
console.log(res[0]); //A的结果
console.log(res[1]); //B的结果
//根据A和B的结果请求C接口数据
setTimeout(() => {
console.log("C的请求结果");
}, 100);
})
.catch((err) => {
console.log(err);
});
二十五、es6去重
//扩展运算符和set结构相结合实现数组和字符串去重
const arr = [
{
name: '张三',
age: 22
},
{
name: '李四',
age: 22
},
{
name: '张三',
age: 23
}
]
let results = arr .map(n => n.name);
let narr1 = [...new Set(results)]
// 数组
let arr = [3, 5, 2, 2, 5, 5];
let unique = [...new Set(arr)]; // [3, 5, 2]
// 字符串
let str = "352255";
let unique = [...new Set(str)].join(""); // "352"
二十六、es6去数组中的值作为对象里的键
const arr = [{date: "2018-11-18", name: "demo1"}, {date: "2018-11-19", name: "demo2"}];
const target = {};
arr.forEach(a => {
const source = JSON.parse(`{"${a.date}":"${a.name}"}`);//利用JSON.parse将对象
//格式直接造出来
Object.assign(target,source);
})
// console.log(target)
// target = {
//"2018-11-18":"demo1",
//"2018-11-19":"demo2"
}
二十七、字符串转数组,数组转字符串
//数组转字符串
//this.form.numberName=[2020-11-02,2020-11-03]
this.form.numberName.toString()//'2020-11-02,2020-11-03'
//字符串转数组
//this.form.numberName='2020-11-02,2020-11-03'
this.form.numberName.split(',')//[2020-11-02,2020-11-03]
二十八、字符串转数组数字
// item.normalMeal.lunch.dishesId "1,2,3,4,5"
this.editForm.soups = item.normalMeal.lunch.dishesId.split(',').map(Number)//[1,2,3,4,5,]
二十九、数组对象里的值累加
creditTotalList.reduce(
(accumulator, currentValue) => accumulator + currentValue.amount,
0,
);
三十、350000转成350,000.00
getCashPledge(num) {
// console.log('getCashPledge押金/保证金', num)
if (num === null || num === undefined) return '';
let r = parseFloat(num).toFixed(2).toString();
const regx = /(\d{1,3})(?=(\d{3})+(?:$|\.))/g;
r = r.replace(regx, '$1,');
return r;
};
三十一、实现并集、交集和差集
let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
// 并集
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}
// 交集
let intersect = new Set([...a].filter(x => b.has(x)));
// set {2, 3}
// a 相对于b的差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}
三十二、数组扁平化处理
//返回是新数组,flat()默认为1,只会拉平一层
[1, 2, [3, [4, 5]]].flat()
// [1, 2, 3, [4, 5]]
[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]
// [[2, 4], [3, 6], [4, 8]].flat()
[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]
三十三、对象里的健和值,组成一个新数组
{ifrs1: "N",ifrs2: "N",ifrs3: "N"}转成
[{questionId:'ifrs1',answer:"N"},{questionId:'ifrs2',answer:"N"},{questionId:'ifrs3',answer:"N"}]
Object.entries(this.leaseformData).map(([key, value]) => ({ questionId: key, answer: value }));