【发布时间】:2023-03-13 00:53:01
【问题描述】:
我有一个保存在状态中的对象数组,并且数组中的每个对象都有另一个对象数组。
这里是单个对象的示例:
id : uuid.v1(),
area : 'Scratch',
name : 'Untitled',
status : "",
size : "",
created : {
name : "username",
time : new Date()
},
modified : {
name : "username",
time : new Date()
},
content: [{
id : uuid.v1(),
Content : "Content 1",
TowerRed : "",
TowerText : "text"
},
{
id : uuid.v1(),
Content : "Content 2",
TowerRed : "",
TowerText : "text"
}]
我需要能够从这些对象内部的内容数组中删除一个对象。
例如我需要删除包含“内容 1”的对象而不修改包含“内容 2”的对象
我曾尝试使用她的反应不变性助手,但没有成功。
在这里,我循环遍历父对象和内容对象,直到找到与“itemID”匹配的 (itemID) 是我要从内容数组中删除的对象的 ID。
var tickerIndex = null;
var tickerItemIndex = null;
for (var i = 0; i < this.state.scratchTickers.length; i++) {
var tickersContent = this.state.scratchTickers[i].content;
tickerIndex = i;
for (var x = 0; x < tickersContent.length; x++) {
if (tickersContent[x].id == itemID) {
tickerItemIndex = x;
}
}
}
然后我创建对父对象及其内容数组的引用:
var item = this.state.scratchTickers[tickerIndex].content;
最后我使用更新不变性帮助拼接数组并根据其 itemID 删除正确的对象:
this.setState ({
scratchTickers: update(item, {
$splice: [[tickerItemIndex, 1]]
})
})
但这似乎不起作用。
这是整个函数:
_deleteTickerItem: function(itemID) {
var tickerIndex = null;
var tickerItemIndex = null;
for (var i = 0; i < this.state.scratchTickers.length; i++) {
var tickersContent = this.state.scratchTickers[i].content;
tickerIndex = i;
for (var x = 0; x < tickersContent.length; x++) {
if (tickersContent[x].id == itemID) {
tickerItemIndex = x;
}
}
}
var item = this.state.scratchTickers[tickerIndex].content;
this.setState ({
scratchTickers: update(item, {
$splice: [[tickerItemIndex, 1]]
})
})
},
【问题讨论】:
-
你可以使用 lodash 的 _.reject() 方法 object.content = _.reject(object.content, {Content: 'Content 1'});
-
@Michael 感谢您的建议,我现在可以使用 _.reject() 函数,知道如何将该对象推入状态保持的对象数组中吗?
var item = this.state.scratchTickers[tickerIndex].content; item = _.reject(item, {id: itemID});
标签: javascript arrays reactjs