目录
多维数组,处理掉里面包含假值的
原数组
[[1, ''], [1, '', null], [1, 1, undefined], [2, 2], [3, 3]]
想要处理成这样
[[2, 2], [3, 3]]
代码(这种只能处理二维数组)
// 方法1
let arr = [[1, ''], [1, '', null], [1, 1, undefined], [2, 2], [3, 3]]
let res = arr.filter(item => {
let flag = item.every(c => c)
if (flag) return item
})
console.log(res)
// 方法2
let newArr = []
arr.forEach(item => {
let flag = item.every(c => c)
if (flag) newArr.push(item)
})
console.log(newArr)
// 方法3
const res1 = arr.map(p => {
const res = p.filter(Boolean)
if (res.length === p.length) {
return p
}
})
console.log(res1.filter(Boolean))
代码2,这种可以处理3维和更高的,用到了递归
let arr = [[1, ''], [1, '', null], [1, 1], [2, 2, [3, [4, '']]], [3, 3, [3, 3, '']]]
const digui = (arr) => {
const res = arr.map(p => {
if (Array.isArray(p)) {
const res = p.filter(Boolean)
if (res.length === p.length) {
// 再判断是不是三维数组甚至更多
if (p.some(c => Array.isArray(c))) {
// console.log(p) // [3, 3, Array(3)]
digui(p)
} else {
return p
}
}
}
})
return res.filter(Boolean)
}
const res = digui(arr)
console.log(res)
只要是对象,外围就用数组包住
原对象
let obj = {
name: "张三",
age: "14",
aa: {
a: "1",
b: "2",
c: "4",
aa: {
a: "1",
b: "2",
c: "4",
aa: {
a: "1",
b: "2",
c: "4",
d: [1, 2, 3]
}
}
}
}
想要处理成这样
let obj =[
{
name: "张三",
age: "14",
aa: [
{
a: "1",
b: "2",
c: "4",
aa: [
{
a: "1",
b: "2",
c: "4",
aa: [
{
a: "1",
b: "2",
c: "4",
d: [1, 2, 3]
}
]
}
]
}
]
}
]
代码,只处理对象,不处理数组
<script>
let obj = {
name: "张三",
age: "14",
aa: {
a: "1",
b: "2",
c: "4",
aa: {
a: "1",
b: "2",
c: "4",
aa: {
a: "1",
b: "2",
c: "4",
d: [1, 2, 3]
}
}
}
}
const digui = (obj) => {
// 得到键的数组
let keys = Object.keys(obj)
// 得到值的数组
let values = Object.values(obj)
// 如果值是对象,则外面包上数组
let newData = values.forEach((item, i) => {
if (typeof (item) === 'object' && !Array.isArray(item)) {
obj[keys[i]] = [item]
digui(item)
}
})
return obj
}
const res = digui(obj)
console.log([res])
</script>
数组变对象,统计出数组中的平均数和总数
需求:
这是我自己想的,处理比较简单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let list = [
{ name: 'a班', count: 3, week: 1 },
{ name: 'b班', count: 4, week: 1 },
{ name: 'c班', count: 5, week: 2 },
{ name: 'a班', count: 3, week: 3 },
{ name: 'b班', count: 4, week: 3 },
]
let obj = {}
list.forEach(item => {
// 存在就+1
if (item.name in obj) {
obj[item.name].total += item.count
++obj[item.name].weekCount
}
// 不存在就创建
else {
obj[item.name] = {
total: item.count,
weekCount: 1
}
}
})
for (const key in obj) {
obj[key].avg = obj[key].total / obj[key].weekCount
delete obj[key].weekCount
}
console.log(obj)
</script>
</body>
</html>
原文链接:https://blog.csdn.net/qq_52845451/article/details/129280375
此处评论已关闭