请求后的代码:
var posts = [
{
"id":268,
"title":{
"rendered":"Koala"
},
"categories":[2]
}
]
var categories = [
{
"id":2,
"name":"Animals"
},
{
"id":3,
"name":"Birds"
},
]
目标: - 创建一个获取posts.categories值的函数,并将其替换为categories.name的匹配id。
结果:
var posts = [
{
"id":268,
"title":{
"rendered":"Koala"
},
"categories":["Animals"]
}
]
我已经四处寻找,但找不到解决方案。有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
我的第一种方法是将类别的ID作为类别数组的位置。
//Let the position be the corresponding id
var categories = [
{
"name":"Humans"
},
{
"name":"Insects"
},
{
"name":"Animals"
},
{
"name":"Birds"
},
]
var posts = [
{
"id":268,
"title":{
"rendered":"Koala"
},
// Requests all data from that categorie posistion
"categories":categories[2]
}
]
console.log(posts);
您要求的方法是:
function FindId(obj, id) {
let max = obj.length;
// Loop to items.
for (let i = 0; i < max; i++)
// Check if id is the same.
if (obj[i]["id"] == id)
// Returns right name.
return obj[i]["name"];
}
var categories = [
{
"id":2,
"name":"Animals"
},
{
"id":3,
"name":"Birds"
},
]
var posts = [
{
"id":268,
"title":{
"rendered":"Koala"
},
"categories":FindId(categories, 2)
}
]
console.log(posts);
答案 1 :(得分:0)
这是一种方法:
<%= f.collection_check_boxes(:role_ids, Role.all, :id, :name) %>
见demo fiddle here。如果您需要支持IE,check here来定义Array.find。