yorickshan
9/2/2018 - 4:21 AM

JS中通过List转Map类型或Json对象实现键值对

//转map类型
var arr =  [
{name: "Name", value: "111"},
{name: "Price", value: "2"},
{name: "ProducingArea", value: "3"},
{name: "ShelfLife", value: "44"},
{name: "Stock", value: "5"}
];
var map = new Map();

//map循环方式
arr.map(function (e, item) {
  map.set(e.name, e.value);
});
  
//$.each循环方式
$.each(arr, function (item, e) {
  map.set(e.name, e.value);
});

//for in 循环方式
for (var item in formArr){
  obj[formArr[item].name] = formArr[item].value;
};
  
Map(5) {"Name" => "111", "Price" => "2", "ProducingArea" => "3", "ShelfLife" => "44", "Stock" => "5"}

map.has('Name')
true

map.get('Name')
"111"

//es6语法
let arr = [{a:1,b:2},{a:3,b:4}];
//获取arr中每个对象的key和value,可以结合map和Object.entries()两个方法来实现
let result = [];
arr.map(o=>{
let map = new Map();
for(let [k, v] of Object.entries(o)){
map.set(k, v);
}
result.push(map);
});

result
(2) [Map(2), Map(2)]
0:Map(2) {"a" => 1, "b" => 2}
1:Map(2) {"a" => 3, "b" => 4}
length:2

//转json对象
var arr =  [
{name: "Name", value: "111"},
{name: "Price", value: "2"},
{name: "ProducingArea", value: "3"},
{name: "ShelfLife", value: "44"},
{name: "Stock", value: "5"}
];
var obj = {};
//循环
$.each(arr, function (item, e) {
  obj[e.name]= e.value;
  });
  
obj
{Name: "111", Price: "2", ProducingArea: "3", ShelfLife: "44", Stock: "5"}

obj['Name']
"111"