js 在数组对象中添加属性和相对应的属性值
程序员文章站
2022-04-25 07:51:40
...
1、先来看个简单的例子
var array = [{"name":"a1"},{"name":"b1"}];
array.forEach((value, index) => {
value.age = 1;
})
结果如下:
2、再来换个例子,objectArray是个数组,里面存放了对象,首先往 objectArray 对象里存放 Key 属性和属性值,再判断 number 是否为空,不为空再往 objectArray 对象里存放 Number 属性和属性值:
开始的对象属性:
var params = {
Name: "name",
Label: {
Objects: [
{ Key: "key1" },
{ Key: "key2" }
]
}
}
var name = $('#Name').val();
var objectName = $('#objectName').val().split(",");
var number = $('#number').val().split(",");
var objectArray = new Array();
var params = {
Name: name,
Delete: {
Objects: objectArray
}
};
for (var i = 0; i < objectName.length; i++) {
var obj = {};
obj["Key"] = objectName[i];
objectArray.push(obj);
}
if (number != null && "" != number) {
objectArray.forEach((value, index) => {
value["Number"] = number[index];
})
}
如果 number 不为空的对象属性:
var params = {
Name: "name",
Label: {
Objects: [
{ Key: "key1", Number: "11" },
{ Key: "key2", Number: "22" }
]
}
}
3、循环往数组 array1 中添加 class 属性
var array1 = [{"name":"a1","shapes":[{"age":12,"sex":"female"}]},
{"name":"b1","shapes":[{"age":10,"sex":"male"}]}];
array1.forEach(item => {
item.shapes.forEach(value => {
value.class = "1";
})
})
结果如下:
感谢以下几篇博客:
https://blog.csdn.net/u012746918/article/details/92622420
https://www.cnblogs.com/mica/p/11759141.html
https://blog.csdn.net/longgeaisisi/article/details/82916476
上一篇: JavaScript——对象
下一篇: 商城登录页面(前端+后端代码)(新)