代码之家  ›  专栏  ›  技术社区  ›  coder

向对象动态添加键/对值

  •  0
  • coder  · 技术社区  · 1 年前

    我的数据是这样的:

    [{
        "key": 111,
        "Students_Info": [{
          "recordId": 111
        }],
        "Adress_Info": {
          "position": 1,-- -- -- > How do I insert this ?
          "city": Delhi
        }
      },
      {
        "key": 222,
        "Students_Info": [{
          "recordId": 222
        }],
        "Adress_Info": {
          "position": 2,-- -- -- > How do I insert this ?
          "city": Delhi
        }
      }
    ]
    

    假设总数组计数为2,我需要在上面提到的位置插入它们的位置。

    这就是我尝试的

    data.forEach((element, value) => {
        data.push("position:"+ value)
    });
    

    但这有语法错误,我不知道如何插入它们。

    1 回复  |  直到 1 年前
        1
  •  2
  •   Arman Charan    1 年前

    有关其他上下文,请参见 Array.prototype.forEach() .

    const data = [
      aDataEntryWithRecordId(111),
      aDataEntryWithRecordId(222),
      aDataEntryWithRecordId(333),
      aDataEntryWithRecordId(444),
      aDataEntryWithRecordId(555),
    ]
    
    data.forEach(
      (entry, index) => {
        const position = index + 1
        entry.Address_Info.position = position
      }
    )
    
    console.log(data)
    
    function aDataEntryWithRecordId(recordId) {
      return {
        key: recordId,
        Students_Info: [{ recordId }],
        Address_Info: { city: 'Delhi' }
      }
    }