需求场景: 假若后端返回这么一个json数据格式,如下所示,需要拿到返回对象中的数组项,或者根据某些指定的条件,取特定的值,然后渲染到页面当中去,例如拿name属性值
{
"ret":true,
"data":{
"headerTitle":"群成员",
"members":{
"A":[
{"id":"0A1","name":"爱美","imgPhoto","http://default.png","phoneNumber":1333344,“age”:18
},
],
"B":[],
"C":[],
"D":[
{"id":"0D1","name":"单滨滨","imgPhoto","http://default.png","phoneNumber":14343344,"age":19
},
],
"E":[],
"F":[],
"H":[
{"id":"0H1","name":"黄师傅","imgPhoto","http://default.png","phoneNumber":14343344
},],
"L":[
{"id":"0L1","name":"小L1","imgPhoto","http://default.png","phoneNumber":14343344,"age":20},
{"id":"0L2","name":"小L1","imgPhoto","http://default.png","phoneNumber":14343344,"age":22}
{"id":"0L3","name":"小L2","imgPhoto","http://default.png","phoneNumber":14343344,"age":21}
]
}
}
}
对应的UI图
从数组对象中拿到特定的值渲染到页面当中,一些新增的方法就很有用了,单纯靠一个for循环就很难搞定了
目标:取对象中的值,然后循环遍历数组
Es5实现方法:先通过对象,方式拿到数组对象,然后for循环,拿到数组项
不同的框架代码中实现的方式语法表现有些不一样
Angular中
// array表示要遍历的数组,obj表示遍历时的每个元素,index表示遍历数组的下标,当然ng中提供 ng-repeat指令也是可以循环遍历
angular.forEach(array,funciton(obj,index){
// dosomething
}
React中:
react中父组件向子组件传值,同样,使用最多是map方法
Vue中
vue中比较粗暴,直接用指令v-for="item in items"可以遍历,比较暴力
下面的是伪代码,仅供参考
var members = {}; // 初始化一个空对象,用于接收后台要返回的对象,然后通过DOM(innerHTML方式,字符串拼接)操作,将数据内填充到页面中指定的位置,当然下面的是伪代码模拟一下
axios.get("/api/mock/linker.json")
.then(res=>{
res = res.data;
if(res.ret == true){
let data = res.data;
this.members = data.members;
}
})
function showName(){
for(key in this.members){
for(var i=0;i<members[key].length;i++){
for(j in members[key]){
console.log(members[key][j].name)
}
}
}
}
}
如下一简单示例所示:从对象中取某一数组中的某个值,从对象中取某一数组中的某个值,与上面的数据格式是一致的
var obj = {
"data":{
"members": [
{"id":111,"name":"小高"},
{"id":222,"name":"小凡"},
{"id":333,"name":"小王"}
]
}
}
var newArrs= []; // 初始化一个空数组
for( key in obj.data){
//console.log(obj.data[key]);
for(let i = 0;i<obj.data[key].length;i++){
console.log(obj.data[key][i]);
for(j in obj.data[key][i]){
console.log(obj.data[key][i].name);
newArrs.push(obj.data[key][i].name);
// break;至于为什么会重复打印两次,因为在里层for-in始终每次都得走一遍,然后在跳到上层for循环,加上break的话,就跳出for-in循环了的,就达到目的了,这里可以浏览器打断点看得出
}
}
}
console.log(newArrs);// (6) ["小高", "小高", "小凡", "小凡", "小王", "小王"]
console.log(new Set(newArrs)); // 去重,{"小高", "小凡", "小王"}
Es6中的forEach实现:
var obj = {
"data":{
"members": [
{"id":111,"name":"小高"},
{"id":222,"name":"小凡"},
{"id":333,"name":"小王"}
]
}
}
var newArrs= [];
obj.data.members.forEach(function(member,index,originArrs){
newArrs.push(member.name);
})
console.log(newArrs); //["小高", "小凡", "小王"]