Lodash remove items recursively

前端 未结 6 738
难免孤独
难免孤独 2020-12-03 22:35

Given this JSON object, how does lodash remove the reach value from the objects?

{ 
    total: 350,
    SN1: { 
        reach: 200,
        enga         


        
6条回答
  •  甜味超标
    2020-12-03 23:02

    There doesn't seem to be a deep omit, but you could iterate over all the keys in the object, and delete reach from the nested objects, recursively:

    function omitDeep(obj) {
      _.forIn(obj, function(value, key) {
        if (_.isObject(value)) {
          omitDeep(value);
        } else if (key === 'reach') {
          delete obj[key];
        }
      });
    }
    

    var obj = { 
      total: 350,
      SN1: { 
        reach: 200,
        engagementRate: 1.35
      },
      SN2: {
        reach: 150,
        engagementRate: 1.19
      }
    };
    
    function omitDeep(obj) {
      _.forIn(obj, function(value, key) {
        if (_.isObject(value)) {
          omitDeep(value);
        } else if (key === 'reach') {
          delete obj[key];
        }
      });
    }
    omitDeep(obj)
    console.log(obj);

提交回复
热议问题