【问题标题】:lodash _.remove not working on an object contentlodash _.remove 不适用于对象内容
【发布时间】:2017-02-09 09:39:16
【问题描述】:

我不能让 lodash _.remove 在看起来像这样的对象内容中工作

content: { 
 code: '8d303377',
 type: 'content',
 repositoryCode: 'default',
 externalLocations: 
  { 
   binaries: 
    { 
      medium: 'http://localhost:4000/image-medium.jpg',
      small: '' 
    } 
  } 
 }

我想删除带有空字符串(小)的条目。我试过这个

 _.remove(content.externalLocations.binaries, function () {
     return content.externalLocations.binaries[req.params.variant] === req.body.url;
 });

req.params.variant == small的值

我也试过这个

_.forEach(content.externalLocations, function (binary) {
    _.remove(binary[req.params.variant], { [req.params.variant]: req.body.url });
});

【问题讨论】:

  • 代码中的 content:.. 块似乎不是有效的 JSON。
  • 二进制文件应该是数组,如果你只想从 json 对象中删除使用 delete obj.binares.somekey
  • 我的不好不是 json 一个 js 对象
  • 正如 Jayant 所说 _remove 需要一个数组 lodash.com/docs/4.17.4#remove

标签: javascript node.js ecmascript-6 lodash


【解决方案1】:

您似乎正试图从binaries 中删除值等于req.body.url 的条目,您可以这样做:

_.each(content.externalLocations.binaries, (value, key, obj) => {
    if (req.params.variant === key && req.body.url === value) {
      _.unset(obj, key);
    }
})

【讨论】:

    【解决方案2】:

    _.remove 状态的文档

    array 中删除所有谓词返回真值的元素,并返回已删除元素的数组 [...]
    强调我的

    您的binaries 对象不是数组。如果您想删除对象属性,请使用delete

    delete content.externalLocations.binaries[req.params.variant];
    

    var content = { 
     code: '8d303377',
     type: 'content',
     repositoryCode: 'default',
     externalLocations: 
      { 
       binaries: 
        { 
          medium: 'http://localhost:4000/image-medium.jpg',
          small: '' 
        } 
      } 
     };
    
    delete content.externalLocations.binaries.small;
    
    console.log(content)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-20
      相关资源
      最近更新 更多