先来一个简单的Array对象
tableData: [
{
id: "1",
name: "显示屏",
brand: "小米",
type: "65寸",
deviceNo: "HW-NJ-E-001",
crux: "N",
clazz: "电器",
fixnumber: "PM-E-001-D",
new1: "aaa",
},
{
id: "2",
name: "笔记本电脑",
brand: "Dell",
type: "灵越5000fit",
deviceNo: "HW-NJ-E-004",
crux: "N",
clazz: "电器",
fixnumber: "无",
new1: "bbb",
},
]
这个数组里有两个对象,我们在添加对象的属性时,如何动态添加对象的属性名呢?
踩坑: 习惯使用“ . ”来获取对象属性
当我们像这样来添加对象的属性名时:
for (var i = 0; i < res.data.content.length; i++)
{
let obj = {};
obj.id = res.data.content[i].id;
obj.name = res.data.content[i].name;
obj.brand = res.data.content[i].brand;
obj.type = res.data.content[i].type;
obj.deviceNo = res.data.content[i].deviceNo;
if (res.data.content[i].crux == true)
{
obj.crux = "Y";
} else if (res.data.content[i].crux == false)
{
obj.crux = "N";
}
obj.clazz = res.data.content[i].clazz;
that.tableData.push(obj);
}
由于我们习惯使用" . "的方式来获取对象属性信息,我们会发现,当我们想创建类似于new1、new2、new3、new4…这样的属性名时,只能通过obj.new1、obj.new2、obj.new3、obj.new4…这样的方式进行,数量少还好,如果让我们新增到new100,new1000,这样的方式显然不可行。
那到底如何快速创建呢?
其实,我们忽视了获取对象属性的另一种途径—— “ [ ] ”
obj.new1 <=> obj[“new1”] <=> obj[“new”+1]
这样一来,new100,new1000就都不是问题了,一个for即可循环解决
for (var j = 0; j < 1000; j++)
{
obj["new" + j] = "new" + j;
}