【问题标题】:How to create a new index array in javascript?如何在javascript中创建一个新的索引数组?
【发布时间】:2021-12-20 16:57:57
【问题描述】:

我有一个数组工具列表

toolList = [{
      tbl_gaveta_NUMERO: '3',
      tbl_gaveta_DESCRIPCION: 'GAVETA CLORO',
      tbl_herramienta_FECHA: '2021-11-02',
      tbl_herramienta_NOMBRE: 'EXACTO',
      tbl_herramienta_CODIGO: '354']}

如何创建另一个索引来添加一个名为 cantidad 的新变量?例如,要分配给候选索引的候选变量。

toolList = [{
      tbl_gaveta_NUMERO: '3',
      tbl_gaveta_DESCRIPCION: 'GAVETA CLORO',
      tbl_herramienta_FECHA: '2021-11-02',
      tbl_herramienta_NOMBRE: 'EXACTO',
      tbl_herramienta_CODIGO: '354',
      cantidad: cantidad]}

【问题讨论】:

    标签: javascript html arrays json


    【解决方案1】:

    使用 JavaScript 方法 push() 将具有索引 'cantidad' 和变量值 cantidad 的新项添加到关联数组:

    let cantidad = 'test';
    
    toolList.push({'cantidad': cantidad});
    

    【讨论】:

    • 非常感谢,但它不起作用。我不知道为什么。
    • @Darwin Quiñones 您能否提供更多信息或代码以便我们可以重现,什么不起作用?
    【解决方案2】:
    let cantidad
    toolList[0]["cantidad"] = cantidad
    

    【讨论】:

      【解决方案3】:

      当变量名匹配对象的键名时,你可以像这样使用 ES6 语法:

      const cantidad = 'cantidad'
      toolList.push({ cantidad })
      

      MDN docs of the push method

      【讨论】:

        猜你喜欢
        • 2018-10-15
        • 2011-02-19
        • 1970-01-01
        • 2023-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 2015-03-13
        相关资源
        最近更新 更多