目录
一、数组对象去重
1.1、需要获取重复数据
1.2、直接过滤filter+findIndex
二、循环对象
三、多层数组对象过滤
一、数组对象去重
1.1、需要获取重复数据
let persons = [
{
"name": "yzq",
"age": 20,
"gender": true,
"height": 10
},
{
"name": "yzq",
"age": 20,
"gender": false,
"height": 20
},
{
"name": "xeon",
"age": 20,
"gender": true,
"height": 30
},
{
"name": "xeon",
"age": 20,
"gender": true,
"height": 180
},
{
"name": "xeon",
"age": 20,
"gender": false,
"height": 180
},
{
"name": "yz1",
"age": 30,
"gender": true,
"height": 180
}
]
let data = [];
persons.forEach(item => {
if (data.length == 0) {
data.push(item);
} else {
let isDiff = true;//是否不同
for (let i = 0; i < data.length; i++) {
let dataItem = data[i];
if (dataItem.name == item.name && dataItem.age == item.age) {
/*集合中已经存在相同数据*/
isDiff = false;
break;
}
}
if (isDiff) {
data.push(item);
}
}
});
// persons = data
console.log(persons, '去重后的数据:', data)
上图左边为去重前,右边为去重后
1.2、直接过滤filter+findIndex
persons = persons.filter(
(obj, index) =>
persons.findIndex(
(item) =>
item.name == obj.name &&
item.age == obj.age
) === index
);
var newArr = this.IsNull.filter((item, index) => {
return this.IsNull.indexOf(item) === index;
});
上面第一种改变自身,第二种不改变自身。
二、循环对象
let obj = {
a: { "name": "xeon" },
b: { "age": 20 },
c: { "gender": false },
}
for (item in obj) {
console.log("obj", item, obj[item]);
}
let key = Object.keys(obj)
let key2 = Object.values(obj)
let key3 = Object.entries(obj);
for (let [key, value] of Object.entries(obj)) {
console.log(key, value);
}
console.log(key, key2, key3);
输出结果:
(1)直接循环对象,用for...in..,可以拿到obj对应的key与values
(2)借助Object.keys()可以将对象的key依次取到,变为一个数组
(3)借助Object.values()可以将对象的values依次取到,变为一个数组
(4)借助Object.entries()返回一个给定对象自身可枚举属性的键值对数组
(5)Vue视图中用v-for循环对象:
<div v-for="(val, key, index) in list">
<span>值:{{ val }}</span>
<span>键:{{ key }}</span>
<span>索引:{{ index }}</span>
</div>
三、多层数组对象过滤
左边为原始数据,根据给定的id取出对应的对象和所在层级。
<script>
let arr = [{
name: '001',
list: [{
id: '913072328433205248',
val: '一组001'
},
{
id: '913072328433101010',
val: '一组002'
}
]
}, {
name: '002',
list: [{
id: '1104405913202069504',
val: '二组001'
}, {
id: '1104405913202076246',
val: '二组002'
}, {
id: '1104406110581821440',
val: '二组003'
}]
}, {
name: '003',
list: [{
id: '6666',
val: '三组001'
}]
}]
let brr = ['1104405913202069504', '913072328433205248', '1104406110581821440']
// let brr = ['1104405913202069504', '1104406110581821440']
// filter():条件是啥,留下的数据就是啥
for (let i = 0; i < brr.length; i++) {
arr.map((it) => {
it.list = it.list.filter((sub, index) => brr.includes(sub.id))
})
}
// 把数组中长度为0的元素删掉==把不为0的留下来
let b = arr.filter((it) => {
return it.list && it.list.length != 0
})
console.log('最终', b);
</script>