Displaying all items within a JSON variable using a for loop instead of just one item at a

Referring to my previously answered question (View Here)

I've created a new JSON variable in PHP and passed it to a JavaScript variable. I have implemented a feature that displays the last read post by the user like this:

 [ //defined by var = book | removed URL for privacy reasons.
    {
        "id": 39,
        "title": "My Pet",
        "url": "https:///novel/my-pet/",
        "chapter": {
            "id": 1192,
            "title": "35",
            "url": "https:///my-pet-35/"
        }
    },
    {
        "id": 37,
        "title": "Nobunaga’s Imouto",
        "url": "https:///novel/nobunagas-imouto/",
        "chapter": {
            "id": 1449,
            "title": "2",
            "url": "https:///nobunaga-imouto-2/"
        }
    },
    {
        "id": 2,
        "title": "Duke's Daughter",
        "url": "https:///novel/dukes-daughter/",
        "chapter": {
            "id": 1398,
            "title": "99",
            "url": "https:///dukes-daughter-99/"
        }
    }
]

The first JSON retrieves data from cookies, enabling users to track their last read post. The second JSON variable displays the newest posts from each category.

[ //defined by var = newest
    {
        "id": 39,
        "title": "My Pet Chapter 35",
        "url": "https:///my-pet-35/",
    },
    {
        "id": 37,
        "title": "Nobunaga’s Imouto Chapter 4",
        "url": "https:///nobunaga-imouto-4/",
    },
    {
        "id": 2,
        "title": "Duke's Daughter Chapter 106",
        "url": "https:///dukes-daughter-106/",
    }
]

To display them, I use a for loop:

    $bookcontainer = $('#release_history'); 
    for (var i in books) {
        var book = books[i];
        var html = '<div class="row"><div class="book_history">';
        html += '<a href="'+book.url+'">'+book.title+'</a></div>';

         // Displaying the latest news

        html += '<div class="newest_history">';
        for (var j in newest) { // displaying the newest post of a category
            var news = newest[j];
            html += '<a href="'+news.url+'">»Chapter '+news.title+'</a></div>';
        }
        html += '</div></div></div>';
        $bookcontainer.append(html);
    }

However, the output appears messed up: https://i.sstatic.net/nBeU1.png

This led me to think about adding an if conditional statement when the IDs match.

            for (var j in newest) {
            var news = newest[j];
            if (news.id == book.id){
                html += '<a href="'+news.url+'">»Chapter '+news.title+'</a></div>';}
            }

Unfortunately, the loop terminates after displaying the initial result. Is there a solution to ensure they are all displayed separately? I aim to show the latest chapters/posts from various categories so users can stay updated on their last read book.

Answer №1

To verify if the index id of both objects match, for instance at index:0 and index:3, they must be identical because verification of containment is not being performed:

Consider this solution:

var book = [ //defined by var = book
    {
        "id": 39, //Category ID
        "title": "Last Read A",
        "url": "Chapter URL A",
    },
    {
        "id": 37, //Category ID
        "title": "Last Read B",
        "url": " Chapter URL C",
    },
    {
        "id": 2, //Category ID
        "title": "Last Read C",
        "url": " Chapter URL C",
    }
]

var book1 = [ //defined by var = newest
    {
        "id": 39, //Category ID
        "title": "Newest Chapter A",
        "url": "Post URL Chapter A",
    },
    {
        "id": 37, //Category ID
        "title": "Newest Chapter B",
        "url": " Post URL Chapter C",
    },
    {
        "id": 2, //Category ID
        "title": "Newest Chapter C",
        "url": " Post URL Chapter C",
    },
    
 //Added a different book with id 10
    {
        "id": 10, //Category ID
        "title": "Newest Chapter C",
        "url": " Post URL Chapter C",
    }
]

const bookIds = book1.map(bookData => bookData.id);

console.log('BookIDS:', bookIds)


book.forEach(bookData => {
  if(bookIds.indexOf(bookData.id) > -1){
    console.log('Matching book found with ID:', bookData.id);
  }
})

Answer №2

Are you specifically interested in identifying which books have not been read by the current user?

const books = [ //stored as variable 'books'
    {
        "id": 39, //Category ID
        "title": "Last Read A",
        "url": "Chapter URL A",
    },
    {
        "id": 37, //Category ID
        "title": "Last Read B",
        "url": " Chapter URL C",
    },
    {
        "id": 2, //Category ID
        "title": "Last Read C",
        "url": " Chapter URL C",
    }
];

const newest = [ //stored as variable 'newest'
    {
        "id": 39, //Category ID
        "title": "Newest Chapter A",
        "url": "Post URL Chapter A",
    },
    {
        "id": 37, //Category ID
        "title": "Newest Chapter B",
        "url": " Post URL Chapter C",
    },
    {
        "id": 2, //Category ID
        "title": "Last Read C",
        "url": " Chapter URL C",
    },

    //Added a different book with id 10
    {
        "id": 10, //Category ID
        "title": "Newest Chapter C",
        "url": " Post URL Chapter C",
    }
];

newBooks = newest.filter(function (element) {
    return books.filter(function (book) {
        if (element.id !== book.id) {
            return false;
        }

        if (element.title !== book.title) {
            return false;
        }

        return element.url === book.url;
    }).length === 0;
});

console.log(newBooks);

The filter function is used to identify entries that meet certain conditions.

In this scenario, I am checking for instances where the filtered book array has a length of zero.

If the length is zero, it means that the user has not read the new chapters.

Hence, the filtered book array provides entries that do not match those in the "newest" array.

Output of the sample:

[ { id: 39, title: 'Newest Chapter A', url: 'Post URL Chapter A' },
{ id: 37, title: 'Newest Chapter B', url: ' Post URL Chapter C' },
{ id: 10, title: 'Newest Chapter C', url: ' Post URL Chapter C' } ]

From the output, we can observe that the entry with id "2" was filtered out since it matched existing data.

Answer №3

Resolved with alteration:

for (var j in newest)

changed to

for (var j = 0; j < newest.length; j++)

I realized it was incorrect to solely use var j in in the second loop in that manner

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

Avoiding repeated execution of event handlers in subviews of Backbone

Working with Backbone, I have a list container view that should house multiple section views with event handling. However, the issue is that the event is triggered as many times as there are subviews inside the container. I understand that moving the clos ...

Unable to execute any actions on object in JavaScript

I currently have two functions in my code: getRawData() and getBTRawData(). The purpose of getBTRawData() function is to retrieve data from Bluetooth connected to a mobile device. On the other hand, getRawData() function takes the return value from getB ...

Utilizing NSURL for constructing new posts on a Rails server via JSON may involve redundant parameters

One problem I'm encountering is that when I make a POST request to a rails server to create a new post using code from the iPhone simulator, the parameters are being sent twice. NSDictionary *thestuff = [NSDictionary dictionaryWithObjectsAndKeys: ...

Typescript: Ways to fix the error 'rxjs/Rx does not have any exported member 'SubscriptionLike'

I'm attempting to replicate the steps outlined in this tutorial found here https://www.youtube.com/watch?v=gxCu5TEmxXE. However, upon running tsc -p, I encounter an error. Is there a specific import that I am missing? ERROR: node_modules/@angular/co ...

The sequence of indices in a for loop and making Ajax requests

I'm dealing with a challenge related to executing ajax requests within a for loop. Despite researching solutions online and implementing them to prevent synchronous request execution, I still face an issue in maintaining the correct order of the succe ...

define` module root path

Currently, I am working with Typescript and my source files are located in the src directory. After transpiling, Typescript generates the output in the lib folder. This means that when I need to import components from my package, I have to specify the full ...

Package.json file is not included in Typescript

Each time I execute tsc, it converts the files to JS format successfully, except for package.json. I want this file included in my output directory. Currently, my tsconfig.json looks like this: { "exclude": ["node_modules"], "compilerOptions": { " ...

Angular: Issue with the functionality of BehaviorSubject

Seeking assistance in retrieving the current value of a BehaviorSubject in Angular. I utilized these lines to print and check its content on the console: console.log(this._isNumeric) console.log(this._isNumeric.getValue()) However, the output shows: close ...

Populate Google Maps with numerous pins using JSON data

I have been working on creating a web application that retrieves data from a server and then plots multiple markers on a Google Map based on the JSON response received. Here is an example of how the JSON response appears: {"key":[{"Latitude":"60.186518", ...

Executing MySQL queries synchronously in Node.js

When working with NodeJS and mysql2 to save data in a database, there are times when I need to perform database saves synchronously. An example of this is below: if(rent.client.id === 0){ //Save client connection.query('INSERT INTO clients (n ...

The creation of numerous DOM elements in D3

I'm currently utilizing the Tableau JS API to develop animated charts with D3.js. Within a Canvas(DOM) element, I am generating the necessary charts using the getUnderlyingData() function. This function is triggered whenever there's a change in f ...

Having trouble including a property in an object using a method that relies on the "this"

Currently, I am attempting to include a property in an object by utilizing a method. Below is the code snippet: const siddhu = { name: 'Siddhu', friends: ['Dylan', 'Jordans', 'Aathi'], setBestFriend: ( ...

Is there a way to extract specific data from a JSON file and calculate the average in order to generate a line graph using JavaScript

I am working with data in json format and I want to create plots using plotly js. Specifically, I need to generate a plot showing different states by semester. To do this, I first need to filter the data for each state (for example, California), calculate ...

Searching for key names in JSON using PHP

Here is the JSON Data I am working with: "12-305":[{"catid":"12","fname":"SALADS","ord":"0","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"All Salads","id":"305","icon":"","price": ...

Enhance DataTables functionality by including the ability to select which script to execute

Currently, I have a DataTables displayed with the provided code, utilizing server-side processing which is functioning properly. I am interested in implementing a dropdown menu above the table that allows users to select from options such as: Product Gr ...

What are the steps to designing customizable drop-down content menus on websites?

I am looking to implement a feature where I can create content drop-down bars similar to the ones shown in the images. When a user clicks on the bar, the content should be displayed, and if clicked again, the drop-down should hide. I have searched for a so ...

Merging and Reorganizing files using Gulp based on Folder names

In my gulpfile.js, I am attempting to configure a setup that concatenates all .js files located in the src/js folder and names them based on their parent folder. Here is an example of the folder structure: project | +-assets | | | +-app.min.js | | | +-ve ...

The attempted upgrade to Highcharts 11 within the Angular App was unsuccessful due to a lack of loader capable of handling the

An issue has been detected in the highcharts.js file located in ./node_modules/highcharts/ at line 8:5207. The module parsing failed due to an unexpected token found at this position. To resolve this error, you may need to set up a suitable loader to proce ...

I require assistance with parsing the JSON outcome within a C# Windows Phone application

As a newbie in the world of developing Windows Phone apps, I am facing an issue that has been persistent even after trying out all possible solutions. The problem arises when my application tries to retrieve data from a web service, and the result it recei ...

Challenge with Sequelize Many-to-Many Query

Currently, I am facing an issue with connecting to an existing MySQL database using Sequelize in Node. The database consists of a products table, a categories table, and a categories_products table. My goal is to fetch products, where each product includes ...