首页 > 解决方案 > 在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}
 };

标签: javascriptreactjs

解决方案


我想你想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);
    }
  };

推荐阅读