我正在使用lodash操作JSON对象。虽然我不反对使用Vanilla JS,但由于我目前只是在进行PoC,因此我只是在寻找最快的解决方案来进行测试。
所以这是我面临的问题:我希望能够轻松地push
元素到对象中的任何位置,并自动创建所有缺失的节点,包括最后一个数组。
例如,假设我有一个空对象,并且我想创建一个函数,可以用正确的值填充我的对象,例如:
let dl = {};
customPush(dl, 'a.b', { c: 3, d: 4 });
// or
customPush(dl, ['a', 'b'], { c: 3, d: 4 });
应该创建:
dl = {
a: {
b: [{
c: 3,
d: 4
}]
}
}
这是我尝试过的所有方法,但它们都无效:
function customPush(obj, path, item) {
// This is just assigning the item to the path, not pushing to a new array
_.set(dl, path, item);
// This one is not doing anything visible
_.get(dl, path, []).push(item);
// Pushing in this one doesn't work with a path like 'a.b'
if (_.has(dl, path)) {
dl.path.push(item);
} else {
_.set(dl, path, [item]);
}
// Any idea?
...
}
非常感谢您的帮助。