javascript - 循环遍历对象的对象
问题描述
所以我有以下函数vanilla JS代码:
function get_menu(menu_id) {
wp.api.loadPromise.done(function() {
const menus = wp.api.collections.Posts.extend({
url: wpApiSettings.root + 'menus/v1/menus/' + menu_id,
});
const Menus = new menus();
Menus.fetch().then(
posts => {
let post_list = posts.items;
console.log(post_list);
});
});
}
get_menu(4);
遍历这些对象并在其中呈现 HTML 的最佳方法是什么?所以假设我想遍历每个对象并获取post_title
并输出 HTML <div> + post_title + </div>
。
所有帮助将不胜感激!
更新:
需要循环渲染:
<div class="column is-one-third is-flex py-0">
<a href=" ***url*** " class="dropdown-item px-2 is-flex is-align-items-center">
<figure class="image is-32x32 is-flex">
<img src=" ***image*** + ***post_title*** '.svg'; ?>">
</figure>
<span class="pl-2"><?= ***post_title*** ?></span>
</a>
</div>
解决方案
您可以遍历数组并创建一个 dom 树
function get_menu(menu_id) {
wp.api.loadPromise.done(function () {
const menus = wp.api.collections.Posts.extend({
url: wpApiSettings.root + 'menus/v1/menus/' + menu_id,
});
const Menus = new menus();
Menus
.fetch()
.then(posts => {
let post_list = posts.items;
// Map through response data and turn objects into elements
const postElements = post_list.map(createDomTree)
// spread all elements from array into arguments for the append method
document.body.append(...postElements)
});
});
}
function createDomTree(post) {
// I'm not sure if these values are available in the response data, but can be replaced
const { post_url, post_title, post_image } = post
const container = document.createElement('div')
container.className = 'column is-one-third is-flex py-0'
const anchor = document.createElement('a')
anchor.href = post_url
anchor.className = 'dropdown-item px-2 is-flex is-align-items-center'
const figure = document.createElement('figure')
figure.className = 'image is-32x32 is-flex'
const img = document.createElement('img')
img.src = `${post_image}${post_title}.svg`
const span = document.createElement('span')
span.className = 'pl-2'
span.textContent = post_title
figure.appendChild(img)
anchor.append(figure, span)
container.appendChild(anchor)
return container
}
get_menu(4);
推荐阅读
- python - Python:按铃铛的顺序生成正态分布
- asp.net - 显示列表
在Gridview中单击按钮/ asp.net - ruby-on-rails - Gem railsconfig/config 通过可安装的 rails 引擎捆绑到应用程序时未加载
- javascript - 为什么每次我运行该函数时我的 if 语句都与 else 交替出现
- javascript - 启用多个文件上传的按钮 - HTML
- javascript - 如何在 for 循环中使用 fetch,等待结果,然后 console.log 它
- javascript - javascript - 字符串对象实例在浏览器和 nodejs 中表现出不同的行为
- mysql - 如何统计每种注册类型的所有参与者?
- c# - 获取异常详情
- python-3.x - PyGame 颜色调整仅适用于三个滑块之一