请求后的代码:
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"]
}
]
我四处寻找,但没有找到解决方案。有人可以帮我解决这个问题吗?
最佳答案
这是一种方法:
function setPostsCategories(posts, categories) {
posts.forEach(function(post) {
var cats = []
post.categories.forEach(function(categorie) {
cats.push(categories.find(function(a) {
return a.id == categorie
}).name);
})
post.categories = cats
})
return posts
}
console.log("post",setPostsCategories(posts, categories));
参见demo fiddle here 。如果需要支持IE,check here定义 Array.find。
关于javascript - Js - 转换对象数据(WP-API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46874770/