1、获取对象的key及value值—Object.entries
1.1 常规对象
const obj = {
id:1,
name:'张三',
age:20
}
for(const [key, value] of Object.entries(obj)){
console.log('key=',key, '-----value=', value)
}
输出结果:
key= id -----value= 1
main.ts:28 key= name -----value= 张三
main.ts:28 key= age -----value= 20
1.2 对象嵌套对象
const obj = {
'学号20230001': {name:'张三', age: 20},
'学号20230002': {name:'李四', age: 20},
'学号20230003': {name:'王五', age: 20},
}
for(const [key, value] of Object.entries(obj)){
console.log('key=',key, '-----value=', value)
}
输出结果:
key= 学号20230001 -----value= {name: '张三', age: 20}
main.ts:28 key= 学号20230002 -----value= {name: '李四', age: 20}
main.ts:28 key= 学号20230003 -----value= {name: '王五', age: 20}
可深层次遍历,循环遍历,取value中的key及value
1.3 对象嵌套数组
const obj = {
'一班': [{id:1, name:'张三', age: 20},{id:2, name:'李四', age: 20}],
'二班': [{id:1, name:'张三二', age: 20},{id:2, name:'李四二', age: 20}]
}
for(const [key, value] of Object.entries(obj)){
console.log('key=',key, '-----value=', value)
}
输出结果:
key= 一班 -----value=
- (2) [{…}, {…}]
- 0: {id: 1, name: '张三', age: 20}
- 1: {id: 2, name: '李四', age: 20}
key= 二班 -----value=
- (2) [{…}, {…}]
- 0: {id: 1, name: '张三二', age: 20}
- 1: {id: 2, name: '李四二', age: 20}
可深层次遍历,循环遍历,取value中的key及value