我有一个 json 对象,如图所示。
this.model = {
"cellType": "RemoveCell",
"maxWidth": "800px",
"items": {
"columns" : [
{"attribute": "existingStrings", "title": "Existing Strings"},
],
"rows" : [
{"existingStrings": this.stringList},
]
}
},
this.stringList 是一个字符串数组(大小不一)。如何在 JSON 对象中声明 this.stringList 以使其以下面这种方式运行?
this.model = {
"cellType": "RemoveCell",
"maxWidth": "800px",
"items": {
"columns" : [
{"attribute": "existingStrings", "title": "Existing Strings"},
],
"rows" : [
{"existingStrings": this.stringList[0]},
{"existingStrings": this.stringList[1]},
{"existingStrings": this.stringList[2]},
...
...
{"existingStrings": this.stringList[n]},
]
}
},
我希望“行”包含一组对象(stringList 中的每个元素对应一个对象)。谢谢
最佳答案
使用函数构建对象列表
this.model = {
"cellType": "RemoveCell",
"maxWidth": "800px",
"items": {
"columns" : [
{"attribute": "existingStrings", "title": "Existing Strings"},
],
"rows" :
(function(){
var objList = [];
for(var i = 0; i < this.stringList.length; i++)
objList.push({"existingStrings":this.stringList[i]});
return objList;
})()
}
},
这是通过使用 IIFE(立即调用的函数表达式)作为“行”的值来实现的。 (function(){})
定义函数表达式。当在表达式之后使用 ()
时,将调用该函数。函数内部是一个 for 循环,它使用 this.stringList
构建一个对象数组。循环结束后,返回数组,即分配给“行”的值。
关于javascript - 如何在 json 中创建对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25187410/