1、根据属性来更新一个数组中的对象
const arr = [ {id: 1, score: 1}, {id: 2, score: 2}, {id: 3, score: 4}];
const newValue = {id: 3, score: 3}
const result = arr.map(x => x.id === newValue.id ? newValue : x);
document.write(JSON.stringify(result) + "<br />")
//或者
const updated = arr.map(function(item){
return item.id == newValue.id ? newValue : item ;
});
document.write(JSON.stringify(updated) + "<br />")
代码提供w3school在线测试
2、数组去重
const numbers = [1, 2, 1, 1, 2, 1, 3, 4, 1 ];
const uniq = [...new Set(numbers)] // => [ 1, 2, 3, 4 ];
const uniq2 = Array.from(new Set(numbers)) // => [ 1, 2, 3, 4 ];
document.write(JSON.stringify(uniq) + "<br />")
document.write(JSON.stringify(uniq2) + "<br />")
代码提供w3school在线测试
3、根据属性删除数组中的一个对象
// 根据属性删除数组中的对象,利用filter进行过滤数组中id相同的项
const initial = [ {id: 1, score: 1}, {id: 2, score: 2}, {id: 3, score: 4}];
const removeId = 3;
const without3 = initial.filter(x => x.id !== removeId);
document.write(JSON.stringify(without3) + "<br />")
代码提供w3school在线测试
4、删除一个对象上的属性(key)
//利用es6的 ...运算符将其他属性和a属性分开来
const obj = {a: 1, b: 2, c: 3};
const {a, ...newObj} = obj;
document.write(JSON.stringify(newObj) + "<br />")
代码提供w3school在线测试
5、两个Set对象相减
//去掉s3中的2和4
const s3 = [ 1, 2, 3, 4, 5, 4, 5, 6, 2, 2, 4 ];
const s2 = [ 2, 4 ];
const subtracted1 = s3.filter(x => s2.indexOf(x) < 0);
document.write(JSON.stringify(subtracted1) + "<br />")
代码提供w3school在线测试
6、数组对象去重
let person = [
{id: 0, name: "小明"},
{id: 1, name: "小张"},
{id: 2, name: "小李"},
{id: 3, name: "小孙"},
{id: 1, name: "小周"},
{id: 2, name: "小陈"},
];
let obj = {};
let peon = person.reduce((cur,next) => {
obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
return cur;
},[]) //设置cur默认类型为数组,并且初始值为空的数组
document.write(JSON.stringify(peon) + "<br />")
代码提供w3school在线测试
7、字符串转bool类型
let flag = 'true';//支持大小写
eval(flag.toLowerCase())
代码提供w3school在线测试
8、获取url地址后参数内容
/**
* 根据传入name获取url后缀中数据
* @param {参数名} name
*/
export const GetQueryString = (name) => {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = decodeURI(window.location.search.substr(1)).match(reg);
if (r != null)return unescape(r[2]);
return null;
}
代码提供w3school在线测试