javascript - 在javascript上合并对象给了我嵌套对象,如何解决?
问题描述
我正在使用 AsyncStorage 处理这些笔记,我的问题出现在我连接新数据之后,它被添加为嵌套对象,这不是我所期望的,所以代码看起来像
addNote = async () => {
try {
var id = this.props.navigation.state.params.data.vhq_id;
var raw = await AsyncStorage.getItem("notes");
var value = JSON.parse(raw);
if (value === null) {
await AsyncStorage.setItem(
"notes",
JSON.stringify({ text: this.state.userinput, id: id })
);
} else {
var note = {
text: this.state.userinput,
id: id,
};
var newData = { value, note };
await AsyncStorage.setItem("notes", JSON.stringify(newData));
}
} catch (erorr) {
console.log(error.message);
}
};
我的输出
Object {
"note": Object {
"id": "c62eb2fe-1647-4e9e-ad21-ce0fb0216948",
"text": "Cccc",
},
"value": Object {
"note": Object {
"id": "c62eb2fe-1647-4e9e-ad21-ce0fb0216948",
"text": "Bbbb",
},
"value": Object {
"id": "c62eb2fe-1647-4e9e-ad21-ce0fb0216948",
"text": "Aaaa",
},
},
}
我不确定为什么会这样,我尝试直接在 concat 函数上添加对象而不使用它作为变量,但它似乎是错误的语法
var newData =
{
value,
{text: this.state.userinput,
id: id}
};
解决方案
我想你想notes
成为一个数组,如果你已经有一个注释,AsyncStorage
你想在数组中添加一个新注释。所以你可能想试试这个
addNote = async () => {
try {
var id = this.props.navigation.state.params.data.vhq_id;
var raw = await AsyncStorage.getItem("notes");
var value = JSON.parse(raw);
if (value === null) {
await AsyncStorage.setItem(
"notes",
JSON.stringify([{ text: this.state.userinput, id: id }]) // See that this is setting an array item to the notes
);
} else {
var note = {
text: this.state.userinput,
id: id,
};
var newData = [ ...value, note ]; // newData is a new array with all items in the value array plus the new note object
await AsyncStorage.setItem("notes", JSON.stringify(newData));
}
} catch (erorr) {
console.log(error.message);
}
};
推荐阅读
- javascript - 在javascript中从数组的数组列表中获取JSON数据
- android - 当我在表单验证中执行一项任务时,我如何在颤振 null 安全中修复此错误
- windows - ReadConsoleA 在程序集中的函数内部崩溃
- python - 如何在python中将值插入二维数组
- python - Flask Flash 消息未在按钮单击时显示
- sql - 使用按帐号分区的先前值填充列
- ssl - 拒绝 IIS 中的所有客户端证书
- swift - 当导航栏被隐藏时,在 SwiftUI 中进行向后滑动手势仅适用于特定视图?
- node.js - 如何使用 db.command() 和 NodeJS 运行原始 MongoDB 操作
- python - 从 scipy.integrate 导入 _arpack 时 DLL 加载失败