[英]how can i set the property in empty object using for loop?
这是我通过表格获取的数据。
var subject = {
"items":[
{
"EmailType":"INVITATION",
"name":"INVITATION",
"subject":"Welcome to Transcendental Meditation India",
"from":"noreply.globalwebsite@tm.org",
"body":"hello",
"active":true,
"confidential":false,
"numberOfDaysToWait":1,
"sequentialOrder":3
},
{
"EmailType":"Create New",
"name":"sweeeee",
"subject":"eeee",
"from":"swa@mail.com",
"body":"hello2",
"active":false,
"confidential":true,
"numberOfDaysToWait":1,
"sequentialOrder":2
}
]}
我正在使用循环来创建另一个对象数组,在修改主题之后,它看起来像这样。
"Catitems": [
{
"template": {
"name": "Series 1 email",
"from": "TEAMGMG",
"subject": "GROUP2 - SERIES1 - EMAIL",
"body": "<html><body><strong>My test email</strong></body></html>",
"confidential": true,
"active": true
},
"sequentialOrder": 1,
"numberOfDaysToWait": 0,
}, {
"template": {
"name": "Series 2 email",
"from": "TEAMGMG",
"subject": "GROUP2 - SERIES2 - EMAIL",
"body": "<html><body><strong>My test email2</strong></body></html>",
"confidential": true,
"active": true
},
"sequentialOrder": 2,
"numberOfDaysToWait": 10,
}
]
我尝试使用此循环操作Subject,但是无法设置属性。
var Catitems={};
for(var i=0; i<subject.items.length ; i++){
Catitems[i]["name"]= subject.items[i].EmailType
}
console.log(item);
您的Catitems
应该声明为object ,而应声明为array :
var Catitems=[];
for(var i=0; i<sobject.items.length ; i++){
var tempObj = {
"template":{} //must set this otherwise some other error
};
tempObj["template"]["name"] = sobject.items[i].EmailType
//tempObj["template"]["somethingElse"] = sobject.items[i].somethingElse
Catitems.push(tempObj);
}
//console.log(item); //not defined btw
console.log(Catitems);
如果要修改数组中的每个元素,则可以使用Array.map将数组中的每个项目映射到新的obj结构。
var subject = { "items": [{ "EmailType": "INVITATION", "name": "INVITATION", "subject": "Welcome to Transcendental Meditation India", "from": "noreply.globalwebsite@tm.org", "body": "hello", "active": true, "confidential": false, "numberOfDaysToWait": 1, "sequentialOrder": 3 }, { "EmailType": "Create New", "name": "sweeeee", "subject": "eeee", "from": "swa@mail.com", "body": "hello2", "active": false, "confidential": true, "numberOfDaysToWait": 1, "sequentialOrder": 2 } ] } const CartItems = subject.items.map((item) => { return { name: item.EmailType, template: { name: item.EmailType, from: item.from, subject: item.subject, body: item.body, confidential: item.confidential, active: item.active }, sequentialOrder: item.sequentialOrder, numberOfDaysToWait: item.numberOfDaysToWait, }; }); console.log(CartItems)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.