在数组中外键一个属性对象,以及覆盖某个属性的值,过滤列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

let items = [
{
id:1,
cid:1,
name:'hello',
price:200
},
{
id:2,
cid:2,
name:'world',
price:100
},
{
id:3,
cid:1,
name:'gobal',
price:2200
}
]
let style= {
'1': {
'color':'red',
'font':'20px'
},
'2': {
'color':'green',
'font':'10px'
}
}

let total = items.map(item=> {
item.style = style[item.cid]
return item
})

console.log(total)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(3) [{…}, {…}, {…}]
0:
cid: 1
id: 1
name: "hello"
price: 200
style: {color: "red", font: "20px"}
1:
cid: 2
id: 2
name: "world"
price: 100
style: {color: "green", font: "10px"}
2:
cid: 1
id: 3
name: "gobal"
price: 2200
style: {color: "red", font: "20px"}
1
2
3
4
5
6
// 函数式调用--过滤符合要求的data
// 常用于过滤搜索列表
let total = items.map(item=> {
item.style = style[item.cid]
return item
}).filter(item=> item.data.includes(`${year}-${month}`))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 覆盖某个属性的值,原理:object.assign()
// 修改某个被点击的title
modify=(edit)=> {
const items = this.state.items.map(item=> {
if(edit === item) {
return {
...item,
title:'修改后的title'
} else {
return item
}
}
})
this.setStete({items}) //手动更新state
}