vue 数组转对象与对象转数组(对象与数组的相互转换)
vue 数组转对象与对象转数组(对象与数组的相互转换)
·
数组转对象
转换前为数组:
转换为对象的效果图:
return{
editScreenVenue:[
{label:'姓名', prop: 'name', size:'12',color: "#000",sort:0},
{label:'单位(公司)', prop: 'company',size:'12',color: "#000",sort:1},
{label:'手机号', prop: 'phone',size:'12',color: "#000",sort:2},
{label:'职务', prop: 'job',size:'12',color: "#000",sort:3},
],//数组数据
}
methods: {
// 数组转对象方法
arrayToObject (arr) {
let map = {};
arr.forEach (item => {
map[item.prop] = {label: item.label, color: item.color, size: item.size};
});
return map;
},
//需要使用数组转对象的方法
getData(){
let newObj= this.arrayToObject(this.editScreenVenue);
console.log(newObj,'newObj');
}
}
数组对象的相互转换
mounted() {
let str = '{"name":{"label":"姓名","color":"#e2534d","size":"12"},"company":{"label":"单位(公司)","color":"#8165a0","size":"12"},"phone":{"label":"手机号","color":"#f9974c","size":"12"},"job":{"label":"职务","color":"#ddd8c3","size":"12"}}';
let json = JSON.parse(str);
let editScreenVenue = Object.entries(json).map(([prop, {label, color, size}]) => ({
label,
prop,
size,
color,
}));
console.log(editScreenVenue,'json转数组');
},
mounted() {
let editScreenVenue = [
{label:'姓名', prop: 'name', size:'12',color: "#000",sort:0},
{label:'单位(公司)', prop: 'company',size:'12',color: "#000",sort:1},
{label:'手机号', prop: 'phone',size:'12',color: "#000",sort:2},
{label:'职务', prop: 'job',size:'12',color: "#000",sort:3},
];
let result = editScreenVenue.reduce((accumulator, current) => {
accumulator[current.prop] = {
size: current.size,
color: current.color,
lable: current.label,
};
return accumulator;
}, {});
console.log(result,'数组转对象');
},
更多推荐
已为社区贡献15条内容
所有评论(0)