三种方法
var mapColumn = { "vdoing" : "访问深度", "_visitorNumber": "访问量", "_pageViews": "浏览量", "_jumpOutRate": "跳出率", "_avgAccessTime": "平均访问时长", "_allTargetConvRate": "转化率", "_orderTotalPrice": "总收益" };
一、原生
var target=[]; var targetl=[]; for (var key in mapColumn) { target.push(key); targetl.push(mapColumn[key]); } console.log(target); console.log(targetl);
二、Jquery
var m_list = []; var m_lists = []; var m_listall = []; $.each(mapColumn,function(key,value){ m_list.push(key); //获取所有的key m_lists.push(value); //获取所有的value m_listall.push({ //获取拼接 title:key, name:value }) }) console.log(m_list); console.log(m_lists); console.log(m_listall);
三、ES6字符串拼接
<div class="part1"></div>
var data = [{ "vdoing" : "访问深度", "_visitorNumber": "访问量", "_pageViews": "浏览量", "_jumpOutRate": "跳出率" },{ "vdoing" : "访问深度1", "_visitorNumber": "访问量1", "_pageViews": "浏览量1", "_jumpOutRate": "跳出率1" }];
for (var i = 0; i < data.length; i++) { /*es6模板字符串*/ $(".part1").append(`<div> <span title="${data[i].vdoing}">${data[i].vdoing}</span> <span title="${data[i]._visitorNumber}">${data[i]._visitorNumber}</span> <span title="${data[i]._pageViews}">${data[i]._pageViews}</span> <span title="${data[i]._jumpOutRate}">${data[i]._jumpOutRate}</span> </div>`); }
从别的地方看到的不错的习题,实际工作中也常用到
一、从某数据库接口得到如下值:
{ rows: [ ["Lisa", 16, "Female", "2000-12-01"], ["Bob", 22, "Male", "1996-01-21"] ], metaData: [ {name: "name", note: ''}, {name: "age", note: ''}, {name: "gender", note: ''}, {name: "birthday", note: ''} ] }
rows是数据,metaData是对数据的说明。现写一个函数,将上面的Object转化为期望的数组:
[ {name: "Lisa", age: 16, gender: "Female", birthday: "2000-12-01"}, {name: "Bob", age: 22, gender: "Male", birthday: "1996-01-21"}, ]
答案:两种,for循环和reduce
var temparry = []; var result = []; for (var k = 0; k < data.metaData.length; k++) { var a = data.metaData[k].name; temparry.push(a); } for (var i = 0; i < data.rows.length; i++) { var ob = {}; for (var j = 0; j < temparry.length; j++) { var name = temparry[j]; ob[name] = data.rows[i][j]; } result.push(ob); } console.log(result);
var result = data.rows.reduce(function(prev1, cur1) { console.log('prev1:' + prev1); console.log('cur1:' + cur1); prev1.push(data.metaData.reduce(function(prev, cur, index) { prev[cur.name] = cur1[index]; return prev; }, {})) return prev1; }, []); //console.log(result); //console.log(result[0]); //console.log(result[1]);
二、数组
a = [ {id: 10001, name: "Lisa", age: 16}, {id: 10002, name: "Bob", age: 22}, {id: 10003, name: "Alice", age: 20}, ];
数组
b = [ {id: 10001, gender: "Female"}, {id: 10002, name: "Bob King", birthday: "1996-01-22"}, {id: 10005, name: "Tom", birthday: "2000-01-01"}, ];
写一个函数按id用b更新a,期望得到的结果为:
[ {id: 10001, name: "Lisa", age: 16, gender: "Female"}, {id: 10002, name: "Bob King", birthday: "1996-01-22", age: 22}, {id: 10003, name: "Alice", age: 20}, {id: 10005, name: "Tom", birthday: "2000-01-01"}, ]
这个自己写吧,不附答案了