将对象转换为存在“等于”属性的对象为“等于”值

时间:2019-02-05 23:30:54

标签: lodash

我下面有一个深层对象,例如cats,我正在寻找一种简单的方法来深层删除所有嵌套属性设置为equal的属性。

const cats = {
  love: {
    meow: {
      equal: 2,
    },
    dolphin: {
      hi: 'meow',
    },
    doggo: true,
    soup: undefined,
    vampire: {},
    deep: {
      ocean: {
        love: {
          equal: 'hi',
        },
      },
    },
  },
};

对此:

const cats = {
  love: {
    meow: 2,
    deep: {
      ocean: {
        love: 'hi',
      },
    },
  },
};

2 个答案:

答案 0 :(得分:1)

您可以使用递归_.transform()

const cats = {
  love: {
    meow: {
      equal: 2,
    },
    dolphin: {
      hi: 'meow',
    },
    doggo: true,
    soup: undefined,
    vampire: {},
    deep: {
      ocean: {
        love: {
          equal: 'hi',
        },
      },
    },
  },
};

const fn = (collection) => _.transform(collection, (r, v, k) => {
  if(_.isArray(v)) r[k] = fn(v);
  else if (_.isObject(v)) {
    if(_.has(v, 'equal')) r[k] =  _.get(v, 'equal');
    else {
      const value = fn(v);
      if(!_.isEmpty(value)) r[k] = value; 
    }
  } else if(!_.isUndefined(v)) r[k] = v;
});

const result = fn(cats);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

答案 1 :(得分:0)

使用@OriDori的答案,我将其自定义为不设置空的/不需要的道具。

const fn = collection => lodash.transform(collection, (r, v, k) => {
  if (lodash.isPlainObject(v)) {
    if (lodash.has(v, 'equal')) {
      r[k] = lodash.get(v, 'equal');
    } else {
      const d = fn(v);
      if (lodash.size(d)) {
        r[k] = d;
      }
    }
  }
});