龙空技术网

Javascript 学习笔记 Map 和 Array 转换

耀眼的笨笨 431

前言:

此时咱们对“js取map”大概比较注重,同学们都想要分析一些“js取map”的相关知识。那么小编同时在网摘上汇集了一些关于“js取map””的相关资讯,希望看官们能喜欢,姐妹们快快来了解一下吧!

对象 2数组

取 key 数组

Object.keys(obj);

取 value 数组

Object.values(obj);

格式化后输出

对象:{"a":1,"b":2,"c":3}

数组:[{"name":"a","value":1}, {"name":"b","value":2}, {"name":"c","value":3}]

var obj = {"a":1, "b":2,"c":3}var arr = Object.keys(obj).map((k) => ({'name': k, 'value': obj[k]}) );console.info(arr);

输出

[    { "name": "a", "value": 1 },    { "name": "b", "value": 2 },    { "name": "c", "value": 3 }]
数组 2 对象

数组:[{"name":"a","value":1}, {"name":"b","value":2}, {"name":"c","value":3}]

对象:{"a":1,"b":2,"c":3}

var arr = [{"name":"a","value":1}, {"name":"b","value":2}, {"name":"c","value":3}];var obj = {};arr.forEach(v => obj[v.name] = v.value);console.info(obj);
var arr = [{"name":"a","value":1}, {"name":"b","value":2}, {"name":"c","value":3}];var obj = arr.reduce((acc, cur) => {acc[cur.name] = cur.value; return acc;}, {});console.info(obj);

如果对象内每个元素都是数组

var obj = arr.reduce((acc, cur) => {	// 格式化单条数据 	var temp = {		title: cur.title,		url: cur.url	};	// 压进数组	acc[cur.key] = acc[cur.key] || [];	acc[cur.key].push(temp);	// 返回累计器	return acc;}, {});
Array 2 Tree
function array2tree(arr, id, pid) {	var id = id || "id"; // id默认叫 id	var pid = pid || "pid"; // 父id默认叫 pid    var rootId = rootId || 0; // 根id默认为 0	var map = {};	var root = [];	var i, len;	// 初始化	len = arr.length;	for (i = 0; i < len; i += 1) {		map[arr[i][id]] = i; 		arr[i].children = [];	}		for (i = 0; i < len; i += 1) {		var item = arr[i];		if (item[pid] === rootId) {  			root.push(item);    		} else {			arr[map[item[pid]]].children.push(item);		}	}		return root;}

使用示例:

async function getTree(id){    var data = await fetch(";)    .then(resp=>resp.json()).then(arr => array2tree(arr));    return id ? data[id] : data;}(function test(){    getTree().then(data => console.log(data));})();

标签: #js取map #数组转tree