2017-05-15 26 views
0

嗨我有兩個數組,裏面有對象。我試圖將標題屬性的哈希值傳遞給另一個具有標題鍵值對的數組對象,但沒有散列(它是一個空字符串)。將鍵值傳遞給另一個長度不同的數組

訣竅是數組未經排序且長度不同。

這是我的代碼:

var res = [ 
 
    [{ 
 
     title: "time goes by", 
 
     searchhash: "" 
 
    }, 
 
    { 
 
     title: "gta vice city", 
 
     searchhash: "" 
 
    }, 
 
    { 
 
     title: "miami beach", 
 
     searchhash: "" 
 
    } 
 
    ], 
 

 
    [{ 
 
     title: "miami beach", 
 
     search_hash: "12456" 
 
    }, 
 
    { 
 
     title: "time goes by", 
 
     search_hash: "98765" 
 
    } 
 
    ] 
 

 
] 
 

 
for (var i = 0; i < res[0].length; i++) { 
 
    if (res[0][i].searchhash === "") { 
 
    titlePass(res[0][i].title) 
 
    res[0][i].searchhash = function hashPass(p) { 
 
     console.log(p); 
 
     i += 1 
 
    } 
 
    } 
 
} 
 

 
function titlePass(t) { 
 
    //Here I'm getting the titles (t) 
 
    res[1].forEach((obj) => { 
 
    if (t === obj.title) { 
 
     hashPass(obj["search_hash"]) 
 
    } 
 
    }) 
 
}

,但我得到hashPass不是一個函數。我知道我可以訪問for循環中hashPass函數的那些值,但是我希望將這些值傳遞給for循環以將其分配給searchhash屬性...

+0

你還沒有顯示你的hashPass函數 - 你有沒有創建一個? – Pete

+0

你會遇到許多問題,試圖這樣做,就像一噸。不要在循環中定義函數,而應該使用forEach循環訪問數組,而不是使用Object.keys來遍歷對象。如果你願意的話,可以給你寫一個例子,但是你需要設法用你自己的數據來實現它。 – Dellirium

回答

1

嗨嘗試下面的代碼。

var res = [ 
    [{ 
     title: "time goes by", 
     searchhash: "" 
    }, 
    { 
     title: "gta vice city", 
     searchhash: "" 
    }, 
    { 
     title: "miami beach", 
     searchhash: "" 
    } 
    ], 

    [{ 
     title: "miami beach", 
     search_hash: "12456" 
    }, 
    { 
     title: "time goes by", 
     search_hash: "98765" 
    } 
    ] 

] 

for (var i = 0; i < res[0].length; i++) { 
    if (res[0][i].searchhash === "") { 
    titlePass(res[0][i]); 
    } 
} 

function titlePass(o) { 
    res[1].forEach((obj) => { 
    if (o.title === obj.title) { 
     o["searchhash"] = obj["search_hash"]; 
    } 
    }) 
} 
2

您是不是要說這個?

var res = [ 
 
    [{ 
 
     title: "time goes by", 
 
     searchhash: "" 
 
    }, 
 
    { 
 
     title: "gta vice city", 
 
     searchhash: "" 
 
    }, 
 
    { 
 
     title: "miami beach", 
 
     searchhash: "" 
 
    } 
 
    ], 
 

 
    [{ 
 
     title: "miami beach", 
 
     search_hash: "12456" 
 
    }, 
 
    { 
 
     title: "time goes by", 
 
     search_hash: "98765" 
 
    } 
 
    ] 
 

 
] 
 

 

 
for (var i = 0; i < res[0].length; i++) { 
 
    var res0 = res[0][i]; 
 
    if (res0.searchhash === "") { 
 
    var title = res0.title; 
 
    for (var j=0;j<res[1].length;j++) { 
 
     var res1 = res[1][j]; 
 
     if (res1.title == title) res0.searchhash=res1.search_hash; 
 
    } 
 
    } 
 
} 
 
console.log(res)

相關問題