lodash _.remove不处理对象内容

时间:2017-02-09 09:39:17

标签: javascript node.js ecmascript-6 lodash

我不能让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 });
});

2 个答案:

答案 0 :(得分:1)

由于您似乎要删除binaries的值等于req.body.url的条目,您可以执行以下操作:

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

答案 1 :(得分:0)

_.remove州的文档

  

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

您的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)