在javascript上合并对象给了我嵌套对象,如何修复它?
我正在使用AsyncStorage处理这些注释,我的问题出现在我收集新数据之后,它被添加为嵌套对象,这不是我所期望的,因此代码看起来是这样的在javascript上合并对象给了我嵌套对象,如何修复它?,javascript,reactjs,Javascript,Reactjs,我正在使用AsyncStorage处理这些注释,我的问题出现在我收集新数据之后,它被添加为嵌套对象,这不是我所期望的,因此代码看起来是这样的 addNote = async () => { try { var id = this.props.navigation.state.params.data.vhq_id; var raw = await AsyncStorage.getItem("notes"); var value
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
中已经有一个note,那么您希望向数组追加一个新的note。所以你可能想试试这个
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);
}
};
预期的结果是什么?您正在
新数据
中存储值
。这是预期的结果。而且,这个问题对于调试来说似乎非常明显,您尝试了什么,哪些有效,哪些无效?