数据结构处理(二)------ 数组和对象的综合应用
前端在请求到后台数据后,我们常常需要对请求过来的数据做一定的处理,从而最终得到我们想要的数据(结构),在这个转化的过程中,我们通常遇到一些字符串/数组/对象之间的转化。可以说,数据处理是前端开发人员最基本的一项技能,而合理的处理方式也往往是我们事半功倍
【案例一】:
将 arrobj = [ { name: 'zhangsan', age: 22 }, { name: 'lisi', age: 36 }, { name: 'wangwu', age: 28 } ] 转化为
形如:arr = [ [{name: 'zhangsan'}, {age: 22}], [{name: 'lisi'}, {age: 36}], [{name: 'wangwu'}, {age: 28 }] ]
var newarr = [] for(let i in arrobj) { var newarr2 = [] for(let j in arrobj[i]) { var newobj = {} newobj[j] = arrobj[i][j] newarr2.push(newobj) } newarr.push(newarr2) } console.log(newarr)
[ 思路 ]:创建一个空的新数组newarr,再往里面push若干空的新数组newarr2,再分别给每个newarr2里面push若干新对象newobj
[ 区分 ]:for in 可遍历对象(key)也可遍历数组(索引值),for of 只可以遍历数组(值)
【案例二】:
将数组 arr = [ { name: "Name", value: "111" }, { name: "Price", value: "2" } ]
转化为 obj = { Name: "111", Price: "2" }
let formArr = [ {name: "Name", value: "111"}, {name: "Price", value: "2"}, {name: "ProducingArea", value: "3"}, {name: "ShelfLife", value: "44"}, {name: "Stock", value: "5"} ]; let o = {} for (let i in formArr) { o[formArr[i].name] = formArr[i].value } console.log(o)
【案例三】:
将对象 obj = { Name: "111", Price: "2" }
转化为 arr = [ { name: "Name", value: "111" }, { name: "Price", value: "2" } ]
let formObj = {Name: "111", Price: "2", ProducingArea: "3", ShelfLife: "44", Stock: "5"} let a = [] let ob = {} for (let i in formObj) { ob[i] = {name:'', value:''} ob[i]['name'] = i ob[i]['value'] = formObj[i] a.push(ob[i]) } console.log(a)
【案例四】:
arr1 = [ { source:1, target:"-3" }, { source:4, target:"-7" } ]
arr1排除source:1的对象,然后把source为其他值的数值放在一个新数组newarr,arr2 = [ { id:"1", name:"a" }, { id:"2", name:"b" }, { id:"3", name:"c" }, { id:"4", name:"d" }]
把newarr中的数字对应arr2中的name找出来,并生成新的json对象,如:[{source:2,name:"b"},{source:5,name:"e"}]
var newarr1 = [] var newarr2 = [] arr1.map(item => { if (item.source !== 1 && newarr1.indexOf(item.source) < 0) { newarr1.push(item.source) } }) console.log(newarr1) newarr1.map(item => { arr2.map(itm => { if(item == itm.id) { newarr2.push({source: item, name:itm.name}) } }) }) console.log(newarr2)
作者:牧羊狼
出处:https://www.cnblogs.com/edwardwzw/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利,谢谢您的配合。
Freedom is not let you do whatever you wanna but teach you not to do the things that you donnot wanna do.