React:使用索引变量更新嵌套集合

React: update nested collections with an index variable

本文关键字:更新 嵌套 集合 变量 索引 React      更新时间:2023-09-26

根据Update插件的文档,我们可以执行以下操作:

var collection = [1, 2, {a: [12, 17, 15]}];
var newCollection = update(collection, {2: {a: {$splice: [[1, 1, 13, 14]]}}});
// => [1, 2, {a: [12, 13, 14, 15]}]

这将访问集合的索引2,键a,并在插入13和14时从索引1开始拼接一个项目(删除17)。

它能为索引字段使用一个变量吗,比如:

var indexOfA = (certain conditions) ? 0 : 1;
var newCollection = update(collection, { indexOfA: {a: {$splice: [[1, 1, 13, 14]]}}});

谢谢。

将索引变量用方括号括起来就可以了:

var newCollection = update(collection, { [indexOfA]: {a: {$splice: [[1, 1, 13, 14]]}}});