将lodash的`_.pull`转换为vanilla JS?

时间:2017-05-05 22:42:30

标签: javascript arrays recursion lodash

我遇到此函数的问题,以递归方式从对象中删除空值:

const _ = require('lodash')

function sanitize(object) {
  Object.entries(object).forEach(([key, val]) => {
    if (
      val == null ||
      Number.isNaN(val) ||
      (typeof val === 'string' && isOnlyWhitespace(val)) ||
      (typeof val === 'object' && Object.keys(sanitize(val)).length === 0)
    ) {
      delete object[key]
    }
  });

    // Remove `undefined` values leftover from using `delete` on an array.
  if (Array.isArray(object)) {
    _.pull(object, undefined); // THIS IS THE LINE IM TRYING TO CHANGE
  }

  return object;
}

function isOnlyWhitespace(str) {
  return !(/\S/).test(str.trim());
}

我试图用香草JS替换_.pull(object, undefined),但似乎没有给出正确的输出(我尝试使用像filter这样的东西。)

以下是您可以运行以查看两个输出的代码段:



// LODASH VERSION
function lodashSanitize(object) {
  Object.entries(object).forEach(([key, val]) => {
    if (
      val == null ||
      Number.isNaN(val) ||
      (typeof val === 'string' && isOnlyWhitespace(val)) ||
      (typeof val === 'object' && Object.keys(lodashSanitize(val)).length === 0)
    ) {
      delete object[key]
    }
  });

  // Remove `undefined` values leftover from using `delete` on an array.
  if (Array.isArray(object)) {
    _.pull(object, undefined); // THIS IS THE LINE IM TRYING TO CHANGE
  }

  return object;
}

// MY VERSION
function mySanitize(object) {
  Object.entries(object).forEach(([key, val]) => {
    if (
      val == null ||
      Number.isNaN(val) ||
      (typeof val === 'string' && isOnlyWhitespace(val)) ||
      (typeof val === 'object' && Object.keys(mySanitize(val)).length === 0)
    ) {
      delete object[key]
    }
  });

  // Remove `undefined` values leftover from using `delete` on an array.
  if (Array.isArray(object)) {
    object = object.filter(val => val != null) // THIS IS MY ATTEMPT
  }

  return object;
}

function isOnlyWhitespace(str) {
  return !(/\S/).test(str.trim());
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<button id="lodash">Show lodash output</button>
<button id="me">Show my output</button>
<p id="output" />
<script>
  /**
   * Fiddle-related code, you can ignore this
   */ 
  const lodashBtn = document.querySelector('#lodash')
  const meBtn = document.querySelector('#me')
  const output = document.querySelector('#output')
  
  function createExampleInput() {
    const input = {
      name: 'John',
      grades: [
        90,
        undefined,
        50,
        null
      ]
    };
    
    return input;
  }
  
  lodashBtn.addEventListener('click', () => {
    output.textContent = JSON.stringify(lodashSanitize(createExampleInput()), null, 4)
  });
  
  meBtn.addEventListener('click', () => {
    output.textContent = JSON.stringify(mySanitize(createExampleInput()), null, 4)
  });
</script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

问题是过滤器返回一个新数组。为什么不使用for循环和拼接:

if (Array.isArray(object)) {
  for (var i = object.length - 1; i >= 0; i--) {
    if (object[i] === undefined) {
      object.splice(i, 1);
    }
  }
}