简体   繁体   English

循环遍历对象的 object

[英]Loop through object of objects

So I have the following function vanilla JS code:所以我有以下 function 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);

This gives me a object of objects as shown below:这给了我一个 object 对象,如下所示: 在此处输入图像描述

What is the best way to loop through these objects and render HTML within?遍历这些对象并在其中渲染 HTML 的最佳方法是什么? So let's say I want to loop through each object and grab the post_title and output HTML <div> + post_title + </div> .所以假设我想遍历每个 object 并获取post_title和 output HTML <div> + post_title + </div>

All help would be appreciated!所有帮助将不胜感激!

Update:更新:

Need to render this in a loop:需要循环渲染:

<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>

You can iterate through the array and create a dom tree您可以遍历数组并创建 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM