![](/img/trans.png)
[英]How can I update the React Native state if I have an array inside an object and the object is inside in a big array?
[英]How can I update a json object inside of an array?
我有一個對象數組,我想更新一些內容。 我想我可以映射對象,找到我要尋找的匹配項,然后更新它。
data = data.map(obj => {
return this.state.objToFind === obj.title;
}).map(obj, idx) => {
console.log("found " + obj.title); // reads found + undefined?
obj.menu = this.state.menu;
obj.title = this.state.title;
obj.content = this.state.content;
});
但是,這不起作用。 我找到了對象,但obj.anything是未定義的。 我的console.log讀取“發現未定義”。
data.map(obj => {
return this.state.objToFind === obj.title;
})
第一個映射將返回true和false的數組,第二個映射將循環遍歷這些值, console.log("found " + obj.title)
將因此顯示“ found + undefined”。
也許您想要這樣的東西。
data = data.filter(obj => {
return this.state.objToFind === obj.title;
}).map(obj, idx) => {
console.log("found " + obj.title);
obj.menu = this.state.menu;
obj.title = this.state.title;
obj.content = this.state.content;
return obj;
});
將其更改為其他變量而不是obj,因為它引用的是an array
父obj 。 還要在第一個函數中使用array.filter,它將返回一個數組,
data = data.filter(obj => {
return this.state.objToFind === obj.title;
}).map(newval, idx) => {
console.log("found " + newval.title);
newval.menu = this.state.menu;
newval.title = this.state.title;
newval.content = this.state.content;
});
Map用於返回變異的對象。 使用map時,您需要返回一些東西,以您的情況為修改對象。
但是,有些事情您做錯了。 1)您正在使用.map搜索內容(這不是您使用map的方式); 嘗試使用.filter或.find 2)使用map更新對象(在第二個函數中)后,您需要將其返回。 情況1:
data = data.filter(obj => {
return this.state.objToFind === obj.title;
}).map(foundObj, idx) => {
console.log("found " + foundObj.title);
foundObj.menu = this.state.menu;
foundObj.title = this.state.title;
foundObj.content = this.state.content;
return foundObj; //updated obj
});
情況2:
var foundObj = data.find(obj => {
return this.state.objToFind === obj.title;
});
console.log("found " + foundObjs.title);
foundObjs.menu = this.state.menu;
foundObjs.title = this.state.title;
foundObjs.content = this.state.content;
如果您只想處理使this.state.objToFind === obj.title
true的那些元素,那么Array.filter
是您所需要的
data = data.filter(obj => {
return this.state.objToFind === obj.title;
}).map(obj, idx) => {
console.log("found " + obj.title); // reads found + undefined?
...
});
甚至簡單
您可以使用some運算符。 (它通過遍歷數組來工作,當您返回true時,它會跳出循環)
data.some(function(obj){
if (obj.title ==== 'some value'){
//change the value here
obj.menu = 'new menu';
obj.title = 'new title';
return true; //breaks out of he loop
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.