嗨我有两个包含对象的数组。我试图将title属性的哈希值传递给另一个具有标题键值对的对象,但没有哈希值(它是一个空字符串)。
诀窍是数组未排序且长度不同。
这是我的代码:
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 :(得分: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)
答案 1 :(得分: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"];
}
})
}