js 对象与数组的互相转换
//对象转数组 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"}