【问题标题】:Push an element anywhere in an object with Lodash使用 Lodash 将元素推送到对象中的任意位置
【发布时间】:2019-04-04 12:39:24
【问题描述】:

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

非常感谢您的帮助。

【问题讨论】:

  • 人们已经在 Lodash herehere 中请求了这种功能。尚未添加,但希望在某个时候会添加。

标签: javascript lodash


【解决方案1】:

您在此处的尝试非常接近:

// 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 进行检查,但如果密钥存在且不包含数组,我不确定您想要做什么。

【讨论】:

    猜你喜欢
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 2022-01-23
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 2013-12-14
    相关资源
    最近更新 更多