给定路径字符串,如
foo.bar[][2]
或 foo.bar[2][]
。我想要一个 set
函数来设置对象中的值。
[]
表示法表示将值压入。
[n]
表示法表示在特定索引中设置值。
您必须创建自己的 mixin 来分割路径、检索现有值并推送新值。
const state = { foo: { bar: [[], [], []] } }
_.mixin({
myPush: function(obj, path, val) {
const [subPath] = path.split(/\[\]/);
_.get(obj, subPath, []).push(val);
}
});
_.myPush(state, 'foo.bar[][2]', 1); // Push 1 on end of `bar`...
_.myPush(state, 'foo.bar[2][]', 2); // Push 2 on end of `bar[2]`
console.log(state);
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>