Add dynamic key, value pairs to JavaScript array or hash table

前端 未结 5 1596
醉话见心
醉话见心 2020-12-12 19:51

I\'m trying to add a key value pair to an existing javascript associative array. The key needs to be a variable. This is for JSON encoding. I realize there are many plugins

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 20:02

    The following code will help you

    ary.push( {[name]: val} );
    

    See below example

    let allData = [{name: "Cat", type: "Animal"}]
    let finalData: any = [];
    for (let i = 0; i < allData.length; i++)
    {
      let obj = allData[i];
      for (let KEY in obj)
      {
        //Pushing data to other array as object
        this.finalData.push({ [KEY] : obj[KEY] });
      }
    }
    

提交回复
热议问题