【问题标题】:iterate array and add new field to each nested array迭代数组并向每个嵌套数组添加新字段
【发布时间】:2018-01-26 04:52:56
【问题描述】:

我有一个来自 AJAX 调用的 JSON 数组,如下所示:

[{field1: "Something", field2: "Other"},{field1: "Something", field2: "Other"},{field1: "Something", field2: "Other"}]

我想在 DataTables 上使用这些数据,但我想根据字段标题(组)向表中的每一行添加一个文本输入。因此,我想将此列添加到每个数组中,例如:

[{field1: "Something", field2: "Other", Group: "Text Input"},{field1: "Something", field2: "Other", Group: "Text Input"},{field1: "Something", field2: "Other", Group: "Text Input"}]

这样 DataTables 将在每个新行上添加一个文本输入。这如何使用 jQuery 或 javascript 实现?

我尝试过遍历数组:

var i, j, arrayItem;
for (i = 0; i < array.length; ++i) {
    arrayItem = array[i];
    arrayItem.push({Group: "Text Input"});
}

但这显示错误,"Push" is not a function。可以看到,JSON数组对于每个嵌套数组都没有明确的索引,每个数组也不是唯一的。

【问题讨论】:

    标签: javascript jquery datatables


    【解决方案1】:

    数组中的条目不是数组,它们是对象。 (数组也是对象,但那些条目不是数组。)要向对象添加属性,简单的方法就是分配给它:

    arrayItem.Group = "text input";
    

    您可以使用 for 循环,这绝对没问题,或者从 ES5 及更高版本(或为过时环境使用 polyfill),您可以使用 forEach

    array.forEach(function(entry) {
        entry.Group = "text input";
    });
    

    这样做的好处是您不需要那些iarrayItem 变量。

    在 ES2015+ 中,您可以使用 for-of 循环:

    for (const entry of array) {
        entry.Group = "text input";
    }
    

    ...具有相同的优势(entry 仅在循环内定义)。

    【讨论】:

    • 我明白了,我如何区分何时引用嵌套对象而不是嵌套数组?我已经为此苦苦挣扎了一段时间哈哈。
    • [...] 表示一个数组。 {...} 表示非数组对象。
    • 我将把这个问题留在这里,因为它可能会在未来帮助其他人:D
    • 感谢您的回答,我很容易理解我的错误。
    【解决方案2】:

    你不能推动,因为它是一个对象。只需分配给对象。

    var fields = [{
      field1: "Something",
      field2: "Other"
    }, {
      field1: "Something",
      field2: "Other"
    }, {
      field1: "Something",
      field2: "Other"
    }]
    
    fields.forEach(x =>
      x.Group = "Text Input"
    )
    console.log(fields)

    【讨论】:

      【解决方案3】:

      {field1: "Something", field2: "Other"} 不是一个数组,它是一个对象。数组用[]包围,对象在{},元素在key: value

      您不使用push() 来添加对象,您只需分配属性。

      array.forEach(e => e.Group = "text Input");
      

      for (var i = 0; i < array.length; i++) {
          array[i].Group = "text Input";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-10
        • 2013-05-05
        • 2015-10-03
        • 1970-01-01
        • 1970-01-01
        • 2020-03-05
        • 2012-08-12
        • 2015-10-17
        相关资源
        最近更新 更多