繁体   English   中英

不可变 JS:在对象内的数组内设置对象中的属性

[英]Immutable JS: Set property in object within array within object

假设我有一个这样的对象:

const document = {
  items: [
    { notes: ['a', 'b'] },
    { notes: ['y', 'z'] },
  ]
}

我想使用 Immutable JS 在一个项目上设置一个 notes 数组。 基本上做一个unshift,但不可变的。

这是我正在尝试的:

const immutableDocument = Immutable.fromJs(document);
immutableDocument.setIn(['items[index]', 'notes'], [newNote, ...oldNotes]);

它不起作用,我在文档中没有看到任何关于通过 Immutable 对象中的某个索引(或谓词)访问数组的内容。

我将如何实现这一点?

更新:基于对这个问题的回答,我还尝试了immutableDocument.setIn(['items', index, 'notes'], [newNote, ...oldNotes]) ,这似乎也不起作用。

这有效:

const newDocument = Immutable.setIn(immutableDocument, ['items', index, 'notes'], [newNote, ...oldNotes]);

不完全确定为什么另一个根据文档不起作用,但是嘿,我继续前进。

暂无
暂无

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

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