当前位置:  开发笔记 > 编程语言 > 正文

用Lodash省略嵌套属性

如何解决《用Lodash省略嵌套属性》经验,为你挑选了2个好方法。

我试图摆脱属性5MinuteRate15MinuteRate以下对象.

var object = { requestsPerSecond:
   { mean: 1710.2180279856818,
     count: 10511,
     'currentRate': 1941.4893498239829,
     '1MinuteRate': 168.08263156623656,
     '5MinuteRate': 34.74630977619571,
     '15MinuteRate': 11.646507524106095 } };

Lodash的omit() - 函数似乎不适用于嵌套对象.以下代码不起作用:

console.log(_.omit(object, 'requestsPerSecond.count'));

编辑:

我尝试了这个,但它不能正常工作:

var subObject = _.omit(object.requestsPerSecond, '5MinuteRate', '15MinuteRate');

console.log(_.merge(object, subObject));

J. Titus.. 6

你快到了.刚分配这将是你的结果subObjectobject.requestsPerSecond.

var object = {
  requestsPerSecond: {
    mean: 1710.2180279856818,
    count: 10511,
    'currentRate': 1941.4893498239829,
    '1MinuteRate': 168.08263156623656,
    '5MinuteRate': 34.74630977619571,
    '15MinuteRate': 11.646507524106095
  }
};

object.requestsPerSecond = _.omit(object.requestsPerSecond, '5MinuteRate', '15MinuteRate');

console.log(object);



1> J. Titus..:

你快到了.刚分配这将是你的结果subObjectobject.requestsPerSecond.

var object = {
  requestsPerSecond: {
    mean: 1710.2180279856818,
    count: 10511,
    'currentRate': 1941.4893498239829,
    '1MinuteRate': 168.08263156623656,
    '5MinuteRate': 34.74630977619571,
    '15MinuteRate': 11.646507524106095
  }
};

object.requestsPerSecond = _.omit(object.requestsPerSecond, '5MinuteRate', '15MinuteRate');

console.log(object);


2> aemonge..:

使用unset:https : //lodash.com/docs#unset,它会变得更干净:

var obj = { 
  requestsPerSecond: { 
    mean: 1710.2180279856818,
    count: 10511,
    'currentRate': 1941.4893498239829,
    '1MinuteRate': 168.08263156623656,
    '5MinuteRate': 34.74630977619571,
    '15MinuteRate': 11.646507524106095 
  } 
};

_.forEach(['requestsPerSecond.5MinuteRate', 'requestsPerSecond.15MinuteRate'], 
  function(omitProperty) {
    obj = _.unset(obj, omitProperty);
  }
);

// Or avoiding the "extra" loop.
obj = _.unset(obj, 'requestsPerSecond.5MinuteRate');
obj = _.unset(obj, 'requestsPerSecond.15MinuteRate');

推荐阅读
围脖上的博博_771
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有