首页 > 解决方案 > 无法理解我想要重构的函数中所需的逻辑

问题描述

目前正在练习我的 JavaScript,我正在努力理解我需要适应的函数的逻辑。该程序背后的想法是将用户输入转换为 JSON。

目前我的程序可以编写如下 JSON:

  {
    "Name": "Jane",
    "Surname": "Doe"
  }

“姓氏:Doe”插入了我试图重构的功能:


addNewParent: function () {
      let infoBoxOne = this.$refs.inputKey.value;
      let infoBoxTwo = this.$refs.inputValue.value;

      //map over the array and set value equal to value
       const new_array = this.objects.map(x => x)

       const last = Object.keys(new_array)[Object.keys(new_array).length-1];
       console.log(last)

      const temp = this.objects.flatMap((obj, index) => {
        if (index === last.length - 1) {
        return { ...obj, [infoBoxOne]: infoBoxTwo };
        }
       return obj;
     });
        this.objects = temp;
     
      document.getElementById("inputKey").value = "";
      document.getElementById("inputValue").value = "";
 
    },


这目前适用于任何不跟随孩子的“父母”:

[
  {
    "Name": "Jane",
    "Surname": "Doe",
    "Age": "45",
    "gender": "female",
    "eyecolor": "blue",
    "haircolor": "red"
  }
]

但是,当我将一个子对象添加到对象中时会出现问题,我现在希望使用相同的函数来定位该子对象。

目前,该对象以“主要”对象为目标并坚持键:值。(如“FROM”下的代码片段所示。我需要它来找到最后一个对象 - 或者子对象并插入键:值或(如果不存在子对象,则在主对象上)并插入键:值 - 由下的代码片段:–</p>

从:


[
  {
    "Name": "Jane",
    "Surname": "Doe",
    "Age": "45",
    "gender": "female",
    "eyecolor": "blue",
    "haircolor": "red",
    "address": {
      "lineone": "17 Summer Hill vue"
    },
    "city": "Some city"
  }
]

至:


[
  {
    "Name": "Jane",
    "Surname": "Doe",
    "Age": "45",
    "gender": "female",
    "eyecolor": "blue",
    "haircolor": "red",
    "address": {
      "lineone": "17 Summer Hill vue",
      "city": "Some city"
    }
  }
]

标签: javascriptjavascript-objects

解决方案


推荐阅读