简体   繁体   English

使用spread运算符更新数组对象对象值

[英]Update array object object value using spread operator

I am trying to update a value from an array object and object. 我试图从数组对象和对象更新值。 my sample code is below. 我的示例代码如下。 Not getting the result as I expected. 没有像我预期的那样得到结果。 It would be nice if someone can help? 如果有人可以提供帮助,那会很好吗?

    let array = [
        {   
            id:"01",
            "name": {
                "value": "jaison",
                "error": null
            },
            "email": {
                "value": "jaison@yopmail.com",
                "error": null
            }
        },
        {
            id:"02",
            "name": {
                "value": "jaison 1",
                "error": null
            },
            "email": {
                "value": "jaison1@yopmail.com",
                "error": null
            }
        }
    ];

    this.state{
        data:array
    }

    //This two data getting a from a form
    const key = "02";
    const editedData = {name:"updated jaison 1", email:"updatedjaison1@yopmail.com"}

    const newData = [...this.state.data];

    const index = newData.findIndex(item => key === item.id);

    let item = newData[index];

    //Working as expcted 
    console.log('1', item);

    Object.keys(editedData).forEach(function (key) {
      item[key] = editedData[key];
    });

    //Working as expcted 
    console.log('2', item);

    this.setState({ data: [...this.state.data, item]}, () => {
        //Not Working as expcted 
        console.log(this.state.data);
    });

    Expected result
   let array = [
    {   
        id:"01",
        "name": {
            "value": "jaison",
            "error": null
        },
        "email": {
            "value": "jaison@yopmail.com",
            "error": null
        }
    },
    {
        id:"02",
        "name": {
            "value": "updated jaison 1",
            "error": null
        },
        "email": {
            "value": "updatedjaison1@yopmail.com",
            "error": null
        }
    }
];

When you update item[key] inside the forEach , it just updates name and email with a string values. 当你更新forEach item[key] ,它只是用字符串值更新nameemail Also, it mutates the state 而且,它改变了state

Instead, you could loop throguh editedData object update the clone of that specific index. 相反,您可以循环throguh editedData对象更新该特定索引的克隆。 Use the spread syntax to keep error and other properties as it is and update only the value property. 使用spread语法保持error和其他属性不变,只更新value属性。 Then update the index of the cloned data array and call setState like this: 然后更新克隆data数组的索引并调用setState如下所示:

const key = "02",
      editedData = { name: "updated jaison 2", email: "updatedjaison2@yopmail.com" },
      data = [...this.state.data],
      index = data.findIndex(item => key === item.id),
      updatedData = { ...data[index] };

// loop through and update only the keys you need 
for(const key in editedData) {
  updatedData[key] = { ...updatedData[key], value: editedData[key] }
}

data[index] = updatedData;

this.setState({ data })

Instead of finding the index and using a forEach to loop over the array, I'd do something like: 我没有找到索引并使用forEach循环遍历数组,而是执行以下操作:

const updatedArray = newData.map(item => {
   // if editedData has a key attribute:
   if (item.id === editedData.key) {
       return editedData; //you'd need to add a key attribute to the data
   } else {
       return item;
   }
});
this.setState({data: updatedArray});

You can just use map : 你可以使用map

   let array = [
        {   
            id:"01",
            "name": {
                "value": "jaison",
                "error": null
            },
            "email": {
                "value": "jaison@yopmail.com",
                "error": null
            }
        },
        {
            id:"02",
            "name": {
                "value": "jaison 1",
                "error": null
            },
            "email": {
                "value": "jaison1@yopmail.com",
                "error": null
            }
        }
    ];

    const key = "02";

    const updated = array.map(item => {
        if (item.id === key) {
            return {id: key, name:"updated jaison 1", email:"updatedjaison1@yopmail.com"}
        }
        return item;
    });

setState({data: updated});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM