简体   繁体   English

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

[英]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.

相关问题 Javascript 更改数组逻辑内 object 内的属性 - Javascript change property inside object within array logic 比较数组中的对象字段 - Compare the object fields within array 将 object 属性值传递给 Typescript Angular 中 object 中的另一个属性 - Pass object property value to another property within that object in Typescript Angular 在使用扩展运算符修改 object 属性时,如何保留数组中 object 的索引? - How can the index of an object within an array be preserved when modifying an object property while using the spread operator? 使用JS / TS将数组中对象的所有属性插入数组中的另一个对象 - Insert all properties from an object within an array to another object in array using JS/TS 如何在 object 属性中转发 TSDoc 描述 - How to forward a TSDoc description within an object property 不可变的 js 对象打字稿接口 - Immutable js object typescript interface 如何通过循环将属性推送到数组内对象内的数组? - How to push properties to an array within an object within an array via looping? 获取对象内的对象数组-尝试与'[object Object]'进行比较时出错 - getting an array of objects within an object - Error trying to diff '[object Object]' 如何订阅rxjs中另一个对象内引用的对象的属性更改 - How to subscribe to the property change of an object referenced within another object in rxjs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM