[英]Immutable JS: Set property in object within array within object
Suppose I have an object like this:假设我有一个这样的对象:
const document = {
items: [
{ notes: ['a', 'b'] },
{ notes: ['y', 'z'] },
]
}
I want to use Immutable JS to set a notes array on an item.我想使用 Immutable JS 在一个项目上设置一个 notes 数组。 Basically do an unshift, but immutable.基本上做一个unshift,但不可变的。
Here is what I am trying:这是我正在尝试的:
const immutableDocument = Immutable.fromJs(document);
immutableDocument.setIn(['items[index]', 'notes'], [newNote, ...oldNotes]);
It's not working, and I don't see anything in the documentation about accessing an array by a certain index (or predicate for that matter) within an Immutable object.它不起作用,我在文档中没有看到任何关于通过 Immutable 对象中的某个索引(或谓词)访问数组的内容。
How would I accomplish this?我将如何实现这一点?
Update: Based on the answer on this question , I also tried immutableDocument.setIn(['items', index, 'notes'], [newNote, ...oldNotes])
, and that does not seem to work either.更新:基于对这个问题的回答,我还尝试了immutableDocument.setIn(['items', index, 'notes'], [newNote, ...oldNotes])
,这似乎也不起作用。
This worked:这有效:
const newDocument = Immutable.setIn(immutableDocument, ['items', index, 'notes'], [newNote, ...oldNotes]);
Not entirely sure why the other one didn't work based on the docs , but hey, I get to move on.不完全确定为什么另一个根据文档不起作用,但是嘿,我继续前进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.