Отображение всех фрагментов вложенного массива

#javascript #jquery #arrays #json

Вопрос:

Я застрял на этом, я не понимаю, почему. У меня есть массив (файл json) со всеми данными моих сообщений, и я хочу отобразить некоторые элементы на своей странице. Мне удалось отобразить простые элементы, но я не могу понять, как отображать каждый элемент вложенного массива. Я хотел бы отобразить все категории слизней для каждого поста. С моей константой post_category я могу получить доступ только к первому слизню.

Итак, вот мой код. Спасибо!

 [{
  "id": 510,
  "slug": "red-bull",
  "title": "Red Bull™",
  "link": "#",
  "thumbnail": "#",
  "category": [{
    "term_id": 7,
    "name": "Identité Visuelle",
    "slug": "iv",
    "term_group": 0,
    "term_taxonomy_id": 7,
    "taxonomy": "categorie",
    "description": "",
    "parent": 0,
    "count": 25,
    "filter": "raw",
    "term_order": "1"
  }, {
    "term_id": 3,
    "name": "Signalétique",
    "slug": "s",
    "term_group": 0,
    "term_taxonomy_id": 3,
    "taxonomy": "categorie",
    "description": "",
    "parent": 0,
    "count": 7,
    "filter": "raw",
    "term_order": "5"
  }]
}, {
  "id": 491,
  "slug": "dogzout-records",
  "title": "Dogzout Records®",
  "link": "#",
  "thumbnail": "#",
  "category": [{
    "term_id": 7,
    "name": "Identité Visuelle",
    "slug": "iv",
    "term_group": 0,
    "term_taxonomy_id": 7,
    "taxonomy": "categorie",
    "description": "",
    "parent": 0,
    "count": 25,
    "filter": "raw",
    "term_order": "1"
  }, {
    "term_id": 6,
    "name": "Vidéo Motion",
    "slug": "vm",
    "term_group": 0,
    "term_taxonomy_id": 6,
    "taxonomy": "categorie",
    "description": "",
    "parent": 0,
    "count": 19,
    "filter": "raw",
    "term_order": "2"
  }]
}, {
  ...
}]
 
 $('#project-loader').on('click', function () {

            let pull_page = 1;
            let jsonFlag = true;

            if (jsonFlag) {
                jsonFlag = false;
                pull_page  ;
                $.getJSON("/bklt-wp/wp-json/projets/all-projects?page="   pull_page, function (data) {
                    if (data.length) {
                        var items = [];

                        $.each(data, function (key, val) {
                            const arr = $.map(val, function (el) { return el });
                            // const post_url = arr[1];
                            const post_title = arr[2];
                            const post_link = arr[3];
                            const post_thumbnail = arr[4];
                            const post_category = arr[5].slug;

                            let item_string = '<li class="project__item"><a href="'   post_link   '" class="project__link" data-project="'   post_category   '">'   post_title   'xa0'   '<div class="project__italic">(<ul class="category__list italic plus"></ul>)</div><span>,'   'xa0'   '</span></a><img src="'   post_thumbnail   '" class="project__img"></li>';
                            items.push(item_string);

                        });

                        for (var i = 0; i < data.length; i  ) {

                            if (data[i]["category"].length > 0) {
                                var outputhtml = "";
                                outputhtml  = "(";
                                outputhtml  = data[i]["category"].map(a => a.slug).join();
                                outputhtml  = ")";
                            }

                            $(".category__list .italic .plus").append('<li class="category__item">'   outputhtml   '</li>');

                        }

                        if (data.length >= 25) {
                            $('li.loader').fadeOut();
                            $(".project__list").append(items);
                        } else {
                            $(".project__list").append(items);
                            $('#project-loader').hide();
                            $('#ajax-no-posts').fadeIn();
                        }
                    } else {
                        $('#project-loader').hide();
                        $('#ajax-no-posts').fadeIn();
                    }
                }).done(function (data) {
                    if (data.length) { jsonFlag = true; }
                });
            }

        });
 

Ответ №1:

Ты хочешь чего-то подобного. отображать слизней родительской категории и их дочерних слизней? Я только что использовал циклы для демонстрации. вы можете получить представление

 var x = [
  {
    id: 510,
    slug: "red-bull",
    title: "Red Bull™",
    link: "#",
    thumbnail: "#",
    category: [
      {
        term_id: 7,
        name: "Identité Visuelle",
        slug: "iv",
        term_group: 0,
        term_taxonomy_id: 7,
        taxonomy: "categorie",
        description: "",
        parent: 0,
        count: 25,
        filter: "raw",
        term_order: "1",
      },
      {
        term_id: 3,
        name: "Signalétique",
        slug: "s",
        term_group: 0,
        term_taxonomy_id: 3,
        taxonomy: "categorie",
        description: "",
        parent: 0,
        count: 7,
        filter: "raw",
        term_order: "5",
      },
    ],
  },
  {
    id: 491,
    slug: "dogzout-records",
    title: "Dogzout Records®",
    link: "#",
    thumbnail: "#",
    category: [
      {
        term_id: 7,
        name: "Identité Visuelle",
        slug: "iv",
        term_group: 0,
        term_taxonomy_id: 7,
        taxonomy: "categorie",
        description: "",
        parent: 0,
        count: 25,
        filter: "raw",
        term_order: "1",
      },
      {
        term_id: 6,
        name: "Vidéo Motion",
        slug: "vm",
        term_group: 0,
        term_taxonomy_id: 6,
        taxonomy: "categorie",
        description: "",
        parent: 0,
        count: 19,
        filter: "raw",
        term_order: "2",
      },
    ],
  },
];
//updated ans:
for (var i = 0; i < x.length; i  ) {

var outputhtml="";
  outputhtml  = x[i]["slug"];
  if (x[i]["category"].length > 0) {
    outputhtml  ="(";
    outputhtml =x[i]["category"].map(a => a.slug).join();
    outputhtml  =")"
  }

console.log(outputhtml);
$(".category__list").append('<li class="category__item">'   outputhtml   '</li>');
}

/* old ans
for (var i = 0; i < x.length; i  ) {
  console.log("parent slug:", x[i]["slug"]);
  if (x[i]["category"].length > 0) {
    for (var j = 0; j < x[i]["category"].length; j  ) {
      console.log("child slug->", x[i]["category"][j]["slug"]);
    }
  }
}
*/ 
 <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- working here. -->
<div class="category__list"></div> 

Комментарии:

1. Спасибо за вашу помощь 🙂 Мне нужен только дочерний слизень, и ваш код, похоже, работает, но не в моем случае, я всегда получаю неопределенное значение. Например, с вашим кодом я получаю : «родительский слизень : не определен»…

2. Можете ли вы обновить вопрос и поделиться обновленным массивом демонстрационных данных? спасибо 🙂

3. Я получаю значения, как и вы, но я не знаю, как отобразить их в html. Для каждого поста я хочу отобразить все категории слизней. Например, для Red Bull мне бы хотелось, чтобы дисплей : Red Bull (iv, s). Вы можете видеть в моем предыдущем коде, что я могу отображать заголовок, но не список слагов для каждого поста.

4. Никто мне не поможет ? Я действительно борюсь уже несколько дней. Я хотел бы отобразить имена моих слизней внутри переменной item_string.

5. я обновил свой ответ, проверьте его. и предоставьте как можно больше информации, чтобы было легко получить решение