使用Lodash在对象中任意位置插入元素

4

我正在使用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?
  ...
}

非常感谢您的帮助。

1
人们在 Lodash 的这里和这里请求了这种函数。目前还没有被添加,但希望在某个时候能够实现。 - Simon East
1个回答

4

你的尝试非常接近:

// 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]);
}

如果数组存在,您只需使用_.get,如果不存在,则使用_.set。您已经在执行后者的部分。

function customPush(obj, path, item) {
  if (_.has(obj, path)) {
    let arr = _.get(obj, path);
    arr.push(item)
  } else {
    _.set(obj, path, [item]);
  }
}

let objOne = { }
let objTwo = { a: [] }

let objThree = { 
  a: {
    b: {
      c: {
      }
    }
  }
}

let objFour = {
  a: {
    b: {
      c: {
        d: []
      }
    }
  }
}

customPush(objOne, "a", "item");
console.log("objOne", objOne);

customPush(objTwo, "a", "item");
console.log("objTwo", objTwo);

customPush(objThree, "a.b.c.d", "item");
console.log("objThree", objThree);

customPush(objFour, "a.b.c.d", "item");
console.log("objFour", objFour);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

值得注意的是,这仅在键不存在或其值为数组时才起作用。如果您提供了指向具有非数组值的现有键的路径,则会出现错误。您可以使用 _.isArray 进行检查,但我不确定如果键存在且不包含数组,您想要做什么。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接