javascript - 无法理解我想要重构的函数中所需的逻辑
问题描述
目前正在练习我的 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"
}
}
]
解决方案
推荐阅读
- javascript - WebUSB navigator.usb 不能用于查看浏览器是否得到支持
- python - Django 外键计数
- git - Git - 我的分支没有使用最新的 master 更新
- javascript - 如何在 Handlebars 中创建一个具有多个逻辑运算符 OR 的助手
- powershell - Powershell 获取输出,向其中添加内容,然后输出到文件
- javascript - 我需要一键为不同的元素添加和删除 2 个不同的类。-jQuery
- android - 如何从 Appium 获取 Android 上下文
- reactjs - TypeError:无法解构“e.target”的属性“名称”,因为它未定义。在 React Hooks 中使用 DatePicker
- html - Vuejs 中的嵌套表
- php - 未捕获的错误:在 bool 上调用成员函数 bind_param(),我不确定我哪里出错了