What is the best way to access nested JSON array data that includes varying key names and content?

In my current project, I am trying to extract data from a JSON array. Here is my approach:

Below is the jQuery/JavaScript code I used to generate and retrieve data, particularly focusing on the nodes object which determines different layouts:

var getPosts = function() {

        $.ajax({
          url: '/wp-json/posts?type=case-studies',
          data: {
            filter: {
            'name': _last
            }
          },
          success: function ( dataS ) {
            //List some global variables here to fetch post data
            // We use base as our global object to find resources we need
            var base = dataS[0];
            console.log(base);
            var postContent = base.content;
            var postTitle = base.title;
            // Main Image ACF object
            var featuredImage = base.meta.main_image;
            // Gallery ACF object
            var nodes = base.meta.work_content;
            // Simple ACF object
            //var textArea = base.meta.work_content[1];
            var items = [];
            for(var i = 0; i < nodes.length; i++)
            {
                var layout = nodes[i];
                var layoutNames = layout.acf_fc_layout;
                items.push( layout.acf_fc_layout['gallery']);
                console.log(layout);
            };
            $('<div>', {
                "class":'loaded',
                html:items.join('')
              }).appendTo(projectContainer);
          },
          cache: false
        });

    };

** edited here with json itself **

The json file here

The order in which these items appear is crucial and cannot be altered. My goal is to individually retrieve each object and insert them into a container using various markup layouts.

Each object has a unique key called acf_fc_layout, so my question is how can I distinguish between the different data based on this key and apply distinct markup for each one? I understand that some may require additional loops to fetch images, etc., and I am prepared for that. It's important to note that there might be multiple instances of the same acf_fc_layout item but with varying content.

Cheers

Answer №1

let elements = [];
let layoutTitles = [];
            for(let i = 0; i < nodes.length; i++)
            {
                let layout = nodes[i];
                layoutTitles.push(layout.acf_fc_layout);
                console.log(layout);
            };
//now iterate through each layoutTitles 
$(layoutTitles).each(function (){
     for(let i = 0; i < nodes.length; i++)
            {                
                let layout = nodes[i];
                if(layout.acf_fc_layout==$(this).val())
                //Perform Operation either image / video / page layout
                console.log(layout);
            };
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deleting content from cells in table for all even td items

This problem has been causing me frustration; I've attempted various methods using jquery and CSS, but to no avail. Essentially, I have the following table structure: <table id="mainTable"> <thead> <tr> <th>Arrival ...

What is the best way to convert a graphql query into a JSON object?

I'm facing an issue where I need to convert a GraphQL query into a JSON object. Essentially, I have a query structured like the example below, and I'm seeking a method to obtain a JSON representation of this query. Despite my efforts in searching ...

Is it possible to pass a function as an argument to another function in jQuery?

My function accepts a JSON object as a parameter containing User id, password, success callback, and error callback. The goal is to authenticate the user using an AJAX service. If the service response is successful, I want to call the success callback fun ...

Validating Two DateTime Pickers as a Group with Javascript in asp.net

How to Ensure Group Validation of Two DateTime Pickers Using JavaScript in ASP.NET ...

AngularJS - Create Alert Pop-Up for Missing Input Fields

I've been struggling to set up my app so that it displays an alert when the user attempts to submit a form with an empty input box. Despite having a confirmation popup working in another part of the application, I can't seem to figure out why thi ...

A guide on adding a hyperlink to a table in Node.js using officegen

Currently, I am utilizing a widely-used Node.js library for generating MS Office Word documents. In the officegen module, the code below is used to create a table. When a raw string is provided to the 'val' property inside the table, it generate ...

When a td element is clicked, the Textbox will also be clicked

Similar Question: Dealing with jQuery on() when clicking a div but not its child $(oTrPlanning).prev().children('td').each(function () { this.onclick = setCountClick; }); When a TD element is clicked, the function setCountClick() i ...

Splitting strings using multiple delimiters in PHP

Here's the structure of my array: {flower},{animals},{food},{people},{trees} I would like to separate the words within curly brackets. This is the code I've used: $array = explode("},{", $list); Upon running this code, the $array loo ...

Ways to incorporate vector .svg images into a D3js tree diagram

var treeData = [ { "name": "Top Level", "parent": "null", "remark":"yes", "children": [ { "name": "Level 2: A", "parent": "Top Level", "remark":"yes", "children": [ { "name": "So ...

Tips for sending a function with arguments in a React application using TypeScript

Is there a way to streamline passing a handleClick function to the son component so that it does not need to be repeated? The code in question is as follows: Mother Component: const Mother = () => { const [selectedOption, setSelectedOption] = useSt ...

Unable to modify the appearance of an HTML element when injected via a Chrome extension

I am currently developing a unique chrome extension that uses Ajax to inject custom HTML into the current tab. This extension appends a <div> element to the body, and now I need to manipulate it using JavaScript. Specifically, I want it to dynamical ...

Using Promises Across Multiple Files in NodeJs

Initially, I had a file containing a promise that worked perfectly. However, realizing the need to reuse these functions frequently, I decided to create a new file to hold the function and used module.export for universal access. When I log crop_inventory ...

What is the solution for jQuery hover show() effect being disabled by an input field?

Here is a simple problem I'm facing: I have created a dropdown menu with a form (login/password) inside that only appears when hovering over the icon and form. The dropdown disappears on mouseleave. Below is the script I am using: $(document).ready( ...

Javascript object attributes

Could you retrieve the value of one object property based on the value of another property? For instance, in an SQL query, is it possible to fetch the id from the object where the object.name equals "somename"? I am trying to obtain the id of a particula ...

PHP Bootstrap Confirmation Dialog Tutorial

Is there a way to implement a delete confirmation dialog? When 'yes' is clicked, the message should be deleted, and when 'no' is clicked, the delete operation should be canceled. At present, this is how it looks in my view: <a href ...

Using Ruby to convert JSON data into an array

This is an example of JSON code containing job and applicant information { "jobs": [ { "id": 1, "title": "Software Developer", "applicants": [ { "id": 1, "name": "Rich Hickey", "tags": ["clojure", "java", "immutability", "datom ...

populating a multi-dimensional array using a "for" loop in Javascript

It appears that JavaScript is attempting to optimize code, causing unexpected behavior when filling a multidimensional array (largeArr) with changing values from a one-dimensional array (smallArr) within a loop. Take the following code for example: largeA ...

Struggling with adding headers in React application

When I try to include an h1 heading, either the heading doesn't show up if I comment out the buttons, or if I comment out the heading, then the buttons don't display. But when both are included, nothing is displayed. Any suggestions on how to fix ...

What could be causing a syntax error when I use `npm run start` with npm react-scripts?

After months of working on a full stack React app, I encountered an unexpected error when trying to run npm run start from the command line. The error message was as follows: // npm run start > [email protected] start /Users/eden/Documents/GitH ...

What is the best jQuery event or method to use for attaching functionality to a dynamic button before it is clicked?

My goal is to connect a jQuery plugin to a button that is dynamically generated. I have attempted the following without success: $('.myButton').on('click', function() { $(this).file().choose(function(e, input) { // ... ...