是否从For ... in循环中插入函数?

时间:2018-11-03 20:07:54

标签: javascript node.js function loops

问题:我尚未声明的函数正在附加到从未分配过的变量的内存空间上?

背景故事:我有一个通过引用比较对象键的值来删除重复对象的脚本。在checkSum变量初始化之后并且紧随其后的For...in loop之后,将函数goodDiver的“ ghost”值添加到变量k

'use strict';

const goodDiver = require('good-diver');

// This package uses good-diver to make things simple :) 
// Read more about it here: https://github.com/starcrusherproductions/good-diver

/**
 * 
 * @param {object} object object you want to truncate
 * @param {array} keysToCheck array of the key's path using good-diver
 * @param {array} keyMustBe array consition of boolean values of what corresponding keysToCheck must be. 
 */

function goodRemover(object, keysToCheck, keyMustBe = Array(keysToCheck.length).fill(true)) { 

  // Initialize c as a count to cycle through the filter later on
  let c = 0;

  // Pump the data into a reference variable
  let reference = object.map(r => {

    // Initialize an empty array to store the keys of duplicates
    let keys = [];

    // Create an iteratable data object call it iterator
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries
    let iterator = object.entries();

    // Iterate through the data object to find the keys
    for (let i of iterator) {

      // THIS IS WHERE THE PROBLEM IS?

      // Create an array called checkSum.  We will see if checkSum[0].length===checkSum[1].length
      let checkSum = [keysToCheck,[]];

      // Debug: Expected result: object [ 'teamName', 'teamId' ] 2
      console.log(typeof(checkSum[0]), checkSum[0], checkSum[0].length);
      // Returned Result: object [ 'teamName', 'teamId' ] 2

      // For each keysToCheck in checkSum[0] 
      for(let k in keysToCheck) {

        // Simplify set keysToCheck[k] to key for simplification
        let key = keysToCheck[k];

        // Debug expected result: string, k
        console.log(typeof(key), k);

        /**
         * Returned: 
         *  string 0
         *  string 1
         *  function goodDiver
         */

        // ^^^ END OF PROBLEM???

        // For object iteration does any of 
        if((i[1].goodDiver(key) === r.goodDiver(key)) === keyMustBe[k] ){

          // Yes push a value to the checkSum 
          checkSum[1].push(true)
        }

      }

      // Does object iteration match a schema?
      if(checkSum[0].length===checkSum[1].length) {

        // Yes push it's keys i[0] into the tracker
        keys.push(i[0]);

      }
    }

    // Return the object keys
    return { keys }
  })

  // Now map through the reference object
  .map(r => {

    // Does object iteration of the reference have more than 1 key?
    if(r.keys.length>1 && r.keys[0]===c) {

      // Yes.  Increment the counter and return just the first element
      c++;
      return r.keys[0];

    }

    // It does not
    else {

      // Increment c.  Return nothing.
      c++;
    }
  })
  // The nature of map returns undefined if there is nothing to return
  // We need to filter out the undefineds and just return stuff that isn't undefined
  .filter(r => {

    // Return boolean test
    return r!=null;
  });

  /**
  * Initialize a new array and iterate through reference to 
  * return data sets that match conditions in reference
  */

  // 
  let newData = [];

  //
  for(let r in reference) {

    newData.push(object[reference[r]]);

  }
  return newData;
}


let objectWithDuplicates = [
  {
    id: 1,
    teamId: 1,
    franchiseId: 2,
    teamName: 'Gulls' 
  },
  {
    id: 2,
    teamId: 1,
    franchiseId: 2,
    teamName: 'Gulls' 
  }]

goodRemover(objectWithDuplicates,['teamName','teamId']);

对goodDiver的引用是我的其他软件包之一,good-diver。如果删除依赖项,则不会将其自身分配给k。 for... in loop是唯一调用goodDiver的地方。它没有分配任何值。它还没有以k的名称声明的变量。确实如此;但是,要开发对象原型。

该条件语句是执行goodDiver的唯一位置。甚至更奇怪的是,如果我评论说goodDiver的条件执行仍然附加在k上?

2 个答案:

答案 0 :(得分:1)

我怀疑您的虚幻函数来自原型链(for..in循环遍历整个链)。您可以尝试改用Object.getOwnPropertyNames()Object.entries()

答案 1 :(得分:1)

虽然这不能直接解决您的问题,但是看起来lodash可以更轻松地实现所需的功能。 get执行与包含的库相同的操作,uniqWith执行过滤。例如:

 let objectWithDuplicates = [
   {
     id: 1,
     teamId: 1,
     franchiseId: 2,
     teamName: 'Gulls' 
   },
   {
     id: 2,
     teamId: 1,
     franchiseId: 2,
     teamName: 'Gulls' 
   }
 ]
    
 const getComparer = keys => (a, b) => {
   return keys.every(k => _.get(a, k) === _.get(b, k))
 }
    
 const result = _.uniqWith(objectWithDuplicates, getComparer(['teamName', 'teamId']))
 
 console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>