如何更改嵌套对象阵列的使用情况
我有一个状态:
const obj = [{id: "1", obj_of_names: [{
id: "a1",
name: "abc",
school: "xyz" },
{ id:"b1",
name: "def",
school: "zyx" },
{ id:"c1",
name: "ghi",
school: "pqr" }]
},
{id: "2", obj_of_names: [{
id: "d1",
name: "abc123",
school: "xyz123" }]
}]
const [newobj, setObj] = useState("obj")
现在我想更新ID:D1内部ID:2的学校。假设旧价值是学校:xyz123现在我想将其更新到学校:newxyz123。 如何使用传播操作员或其他方法来实现这一目标?
我尝试了以下代码:
setObj((prevObjects) => {
const tempIndex = prevObjects.findIndex(
(item) => item.id === reqdImgID
);
const newObject = obj[tempIndex].obj_of_names.map((obj) => {
if (obj.id == reqdID) {
return { ...obj,
school: newSchool,};}
return obj; }););
但是我将其作为OUPUT: { id:“ C1”, 名称:“ Ghi”, 学校:“ newxyz123” }
I have a state:
const obj = [{id: "1", obj_of_names: [{
id: "a1",
name: "abc",
school: "xyz" },
{ id:"b1",
name: "def",
school: "zyx" },
{ id:"c1",
name: "ghi",
school: "pqr" }]
},
{id: "2", obj_of_names: [{
id: "d1",
name: "abc123",
school: "xyz123" }]
}]
const [newobj, setObj] = useState("obj")
Now I want to update school for the id:d1 inside id:2. Suppose the old value is school: xyz123 now I want to update it to school: newxyz123.
How can I achieve this using the spread operator or by another method?
I tried the below code:
setObj((prevObjects) => {
const tempIndex = prevObjects.findIndex(
(item) => item.id === reqdImgID
);
const newObject = obj[tempIndex].obj_of_names.map((obj) => {
if (obj.id == reqdID) {
return { ...obj,
school: newSchool,};}
return obj; }););
But I am getting this as an ouput:
{
id:"c1",
name: "ghi",
school: "newxyz123"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议创建一个接收原始数组,匹配器函数和替换功能的函数。此功能的目的是返回具有更改值的新数组。
然后,使用该函数替换值。
这将做什么:
obj_of_names
查找ID为“ D1”的对象。obj_of_names
对象克隆的新对象,其中包含替换的学校价值。当然,您可以通过使用各种库克隆对象,突变并返回新对象来提高此代码及其可读性,但是如果您想开始使用,则可以解决。
另外,如果您想更改学校名称,建议使用@aweimon引用的答案,但是如果您想在各种标准上更改多个对象,则可以改善上述功能。
I suggest creating a function that receives the original array, a matcher function, and a replace function. The purpose of this function is to return a new array with the value changed.
Then, use the function to replace the values.
What this will do:
obj_of_names
to find the object where the id is "d1".obj_of_names
object, which contains the replaced school value.Of course, you can improve this code and its readability by using various libraries to clone the objects, mutate them, and return new objects, but it is a workaround if you want to get started.
Also, if you want to change the school name, I suggest using the answer @aweimon referenced, but if you want to change multiple objects on various criteria, you can improve the function above.
您可以在另一个映射中调用映射,然后更改阵列whitin whitin the对象:
然后您可以调用
setState
并使用newarr
更新它。You can call a map inside another map and change the array whitin the object like so:
Then you can call
setState
and update it with thenewArr