代码之家  ›  专栏  ›  技术社区  ›  leonardofed

通过两个数组循环构建对象

  •  0
  • leonardofed  · 技术社区  · 6 年前

    很简单。

    objOfMatches 它接受两个数组和一个回调。objOfMatches将构建一个对象并返回它。要构建对象, 对象匹配

    function objOfMatches(array1, array2, callback) {
        //create obj
        var obj = {}
    
        //loop thru first array
        for(let i = 0; i < array1.length; i++) {
            for (let j = 0; j < array2.length; j++) {
                if (callback(array1[i]) === array2[j]) {                
                    obj.array1[i] = array2[j];
                }
            }
        }
        return obj;
    }
    
    console.log(objOfMatches(['hi', 'howdy', 'bye', 'later', 'hello'], ['HI', 'Howdy', 'BYE', 'LATER', 'hello'], function(str) { return str.toUpperCase(); }));
    // should log: { hi: 'HI', bye: 'BYE', later: 'LATER' }
    

    看起来很简单,但我不完全理解为什么它会在控制台中抛出一个TypeError。 (TypeError: Cannot set property '0' of undefined)

    有人能解释一下发生了什么事吗?

    3 回复  |  直到 6 年前
        1
  •  1
  •   Mark    6 年前

    元素不需要在两个数组中循环。您可以遍历其中一个并使用索引在另一个中查找相应的对象。

    reduce()

    function objOfMatches(arr1, arr2, callback){
      return arr1.reduce((obj, current, index) => {
        if(arr2[index] === callback(current)) obj[current] = arr2[index]
        return obj
      }, {})
    }
    
    console.log(objOfMatches(['hi', 'howdy', 'bye', 'later', 'hello'], ['HI', 'Howdy', 'BYE', 'LATER', 'hello'], function(str) { return str.toUpperCase(); }));
        2
  •  1
  •   connexo    6 年前

    假设两个数组的长度相等,并且匹配元素的索引匹配,那么一个非常简单的reduce就可以实现:

    const x = ['hi', 'howdy', 'bye', 'later', 'hello'],
          y = ['HI', 'Howdy', 'BYE', 'LATER', 'hello'];
    
    console.log(x.reduce((a,v,i)=>Object.assign(a,{[v]:y[i]}),{}))

    如果您需要检查匹配的存在和位置,这就是您需要修改的内容 Array.prototype.reduce

    const x = ['hi', 'later', 'howdy', 'bye', 'hello', 'foo'],
          y = ['HI', 'baz', 'Howdy', 'BYE', 'LATER', 'hello', 'bar'];
    
    console.log(x.reduce((a,v)=> {
        let i = y.indexOf(v.toUpperCase())
        return i === -1 ? a : Object.assign(a, {[v]:y[i]})
      },{}
    ))
        3
  •  0
  •   Emeeus    6 年前

    按照你的方法,你应该用这个 obj[array1[j]] = array2[i]

    function objOfMatches(array1, array2, callback) {
        //create obj
        var obj = {}
    
        //loop thru first array
        for(let i = 0; i < array1.length; i++) {
            for (let j = 0; j < array2.length; j++) {
                if (callback(array1[i]) === array2[j]) {   
                    if(!array1[j] in obj) obj[array1[j]]  = [] 
                    obj[array1[j]] = array2[i];
                }
            }
        }
        return obj;
    }
    
    console.log(objOfMatches(['hi', 'howdy', 'bye', 'later', 'hello'], ['HI', 'Howdy', 'BYE', 'LATER', 'hello'], function(str) { return str.toUpperCase(); }));