把对象转化为数组
var obj={"one":"I am 1","two":"I am 2"};
//方法一(1)
var arr = Object.getOwnPropertyNames(obj); //arr=["one", "two"]
var valArr = arr.map(function(i){return obj[i]});//["I am 1", "I am 2"]
//方法一(2)
var arr2 = Object.keys(obj);//arr=["one", "two"]
var valArr2 = arr2.map(function(i){return obj[i]});//["I am 1", "I am 2"]
//方法一(3) 直接合并,一条代码解决
var valArr22 = Object.keys(obj).map(function(i){return obj[i]});//["I am 1", "I am 2"]
//方法二
let arr1 = []
let obj1 = { dr: "dr001",ljy: "ljy002" }
for (let prop in obj1) {
arr1.push({name: prop,ct: obj1[prop]})}
console.log('arr', JSON.stringify(arr1, "null", 2));
// arr [
// {
// "name": "dr",
// "ct": "dr001"
// },
// {
// "name": "ljy",
// "ct": "ljy002"
// }
// ]
console.log(arr1);
// (2) [{…}, {…}]
// 0: {name: "dr", ct: "dr001"}
// 1: {name: "ljy", ct: "ljy002"}
// length: 2
// __proto__: Array(0)
把对数组转为对象
let arr2 = [{
name: 'dr',
ct: 'dr001'
},
{
name: 'ljy',
ct: 'ljy002'
}]
let obj2 = {}
arr2.forEach(item => {
obj2[item.name] = item.ct
})
console.log('obj2', JSON.stringify(obj2, null, 2));
// obj2 {
// "dr": "dr001",
// "ljy": "ljy002"
// }
console.log(obj2);
// {dr: "dr001", ljy: "ljy002"}
var a = [1,2,3,4,5]
Object.assign({},[1,2,3])
//{0: 1, 1: 2, 2: 3}
{...['a','b','c']}
//{0: "a", 1: "b", 2: "c"}
var a = [
"dwadmin",
"rladmin",
"ypadmin",
"ocradmin",
"admin",
"cvadmin"
]
转为
var b =[
{ "value": "dwadmin"},
{ "value": "rladmin"},
{ "value": "ocradmin"},
{ "value": "admin"},
{ "value": "cvadmin"},
{ "value": "dwadmin"},
];
var b = []
a.forEach((v, i) => {
b.push({
value: v
})
})