javascript - 如何在 json 中创建对象数组?

标签 javascript json

我有一个 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/

相关文章:

php - 如何从js代码中获取字符串值

javascript - 滚动过标题后出现 DIV 导航

javascript - 通过匹配值数组来对 javascript 对象文字进行子集化

sql - 使用 Postgres 在 json 数组中索引对象元素

json - 在 go 中,什么是 json.Unmarshal 最大深度?

android - 照片未出现在 RecyclerView 中

javascript - JSON 对象中的数组长度返回未定义

json - 非常长的对象数组的 NodeJS JSON.stringify 错误 "invalid string length"

javascript - 将键值对添加到 javascript 中的对象数组?

javascript - 页面刷新时丢失数据