How to extract a collection of distinct objects from JSON using JavaScript

{"result":[[{"Image":{"__type":"File","name":"tfss-772aedb6-2767-4935-88f8-ae9280bc512b-expendables.jpg","url":"http://files.parsetfss.com/49a11e0f-0c84-417e-b81b-58f5e97abae9/tfss-772aedb6-2767-4935-88f8-ae9280bc512b-expendables.jpg"},"Title":"The Expendables 3","featured_actors":" Sylvester Stallone, Jason Statham, Jet Li","genre ":"Action, Adventure, Thriller","imdb_rating":6.3,"plot_summary":"Barney augments his team with new blood for a personal battle: to take down Conrad Stonebanks, the Expendables co-founder and notorious arms trader who is hell bent on wiping out Barney and every single one of his associates.","running_time_mins":126,"trailer_video_link":"http://www.imdb.com/rg/VIDEO_PLAY/LINK//video/imdb/vi1896197145/","viewer_rating":"18","objectId":"8cTkg769gM","createdAt":"2014-08-16T21:32:28.318Z","updatedAt":"2014-08-16T21:35:56.217Z","__type":"Object","className":"Movie"}],[{"Image":{"__type":"File","name":"tfss-65707002-e78b-47bd-9c7a-da072f388e25-deliver.jpg","url":"http://files.parsetfss.com/49a11e0f-0c84-417e-b81b-58f5e97abae9/tfss-65707002-e78b-47bd-9c7a-da072f388e25-deliver.jpg"},"Title":"Deliver Us From Evil","featured_actors":"Eric Bana, Édgar Ramírez, Olivia Munn","genre":"Crime, Horror, Thriller","imdb_rating":6.5,"plot_summary":"New York police officer Ralph Sarchie investigates a series of crimes. He joins forces with an unconventional priest, schooled in the rites of exorcism, to combat the possessions that are terrorizing their city.","running_time_mins":118,"trailer_video_link":"http://www.imdb.com/video/imdb/vi1746054425/?ref_=tt_ov_vi","viewer_rating":"15","objectId":"BoCM1zbOvh","createdAt":"2014-08-25T14:27:24.331Z","updatedAt":"2014-08-25T19:49:09.910Z","__type":"Object","className":"Movie"},{"Image":{"__type":"File","name":"tfss-772
aedb6-2767-4935-88f8-ae9280bc512b-expendables.jpg","url":"http://files.parsetfss.com/49a11e0f-0c84-417e-b81b-58f5e97abae9/tfss-772aedb6-2767-4935-88f8-ae9280bc512b-expendables.jpg"},"Title":"The Expendables 3","featured_actors":" Sylvester Stallone, Jason Statham, Jet Li","genre":"Action, Adventure, Thriller","imdb_rating":6.3,"plot_summary":"Barney augments his team with new blood for a personal battle: to take down Conrad Stonebanks, the Expendables co-founder and notorious arms trader who is hell bent on wiping out Barney and every single one of his associates.","running_time_mins":126,"trailer_video_link":"http://www.imdb.com/rg/VIDEO_PLAY/LINK//video/imdb/vi1896197145/","viewer_rating":"18","objectId":"8cTkg769gM","createdAt":"2014-08-16T21:32:28.318Z","updatedAt":"2014-08-16T21:35:56.217Z","__type":"Object","className":"Movie"}]]}

After receiving this JSON response via curl, I am attempting to extract unique objects from the array. However, it seems to be returning a duplicate of the first object at the end, despite my efforts using various methods such as Underscore.js _.uniq. Any assistance or suggestions on how to solve this issue would be greatly appreciated. Thank you for your help in advance.

Below is the code I have implemented:

Parse.Promise.when(promises).then(
    function() {
        var result = [];
        _.each(arguments, function(object) {
            result.push(object); // each object is an array of movieIds
        });

        var movies = _.flatten(result);
        var uniqueMovies = _.uniq(movies, function(movie){
                                            return movie.Title;
        });

        response.success(uniqueMovies);
    },
    function(error) {
        response.error(error);
    }
);
///
});

Answer №1

Upon further investigation, I noticed that the duplicate "image" object you mentioned is nested within the second object. To tackle this issue, I came up with a solution by looping through the JSON object and extracting only the first element from each loop iteration. You can check out the updated code snippet here: http://jsfiddle.net/csdtesting/527oevbc/

    var data = {
      "result": [
        [{
          "Image": {
            "__type": "File",
            "name": "tfss-772aedb6-2767-4935-88f8-ae9280bc512b-expendables.jpg",
            "url": "http://files.parsetfss.com/49a11e0f-0c84-417e-b81b-58f5e97abae9/tfss-772aedb6-2767-4935-88f8-ae9280bc512b-expendables.jpg"
          },
          "Title": "The Expendables 31",
          "featured_actors": " Sylvester Stallone, Jason Statham, Jet Li",
          "genre": "Action, Adventure, Thriller",
          "imdb_rating": 6.3,
          "plot_summary": "Barney augments his team with new blood for a personal battle: to take down Conrad Stonebanks, the Expendables co-founder and notorious arms trader who is hell bent on wiping out Barney and every single one of his associates.",
          "running_time_mins": 126,
          "trailer_video_link": "http://www.imdb.com/rg/VIDEO_PLAY/LINK//video/imdb/vi1896197145/",
          "viewer_rating": "18",
          "objectId": "8cTkg769gM",
          "createdAt": "2014-08-16T21:32:28.318Z",
          "updatedAt": "2014-08-16T21:35:56.217Z",
          "__type": "Object",
          "className": "Movie"
        }],
        [{
          "Image": {
            "__type": "File",

            //rest of the JSON data...

I hope this solution meets your requirements!</p>
    </div></answer1>
<exanswer1><div class="answer" i="26197236" l="3.0" c="1412442819" m="1412459801" a="R2lhbm5pcyBHcml2YXM=" ai="3992740">
<p>I observed that the duplicate "image" object mentioned by you is nested inside the second one which led me to iterate through the JSON object and extract just the first element from each iteration.
For reference, here is the updated version: <a href="http://jsfiddle.net/csdtesting/527oevbc/" rel="nofollow">http://jsfiddle.net/csdtesting/527oevbc/</a></p>

<p><div>
<div>
<pre class="lang-js"><code>    var data = {
      "result": [
        [{
          "Image": {
            "__type": "File",
            "name": "tfss-772aedb6-2767-4935-88f8-ae9280bc512b-expendables.jpg",
            "url": "http://f iles.parsetfss.com/49a11e0f-0c84-417e-b81b-58f5e97abae9/tfss-772aedb6-2767-4935-88f8-ae9280bc512b-expendables.jpg"
          },
          "Title": "The Expendables 31",
          "featured_actors": " Sylvester Stallone, Jason Statham, Jet Li",
          "genre": "Action, Adventure, Thril ler",
          "imdb_rating": 6.3,
          "plot_summary": "Barney augments his team with new blood for a personal battle: to take down Conra d Stonebanks, the Expendables co-founder and notorious arms trader who is hell bent on wiping out Barney and every singl e one of his associates.",
          "running_time_mins": 126,
          "trailer_video_link": "http://www.imdb.com/rg/VIDEO_PLAY/LINK//video/im db/vi1896197145/",
          "viewer_rating": "18",
          "objectId": "8cTkg769gM",
          "createdAt": "2014-08-16T21:32:28.318Z",
          "updatedAt": "2014- 08-16T21:35:56.217Z",
          "__type": "Object",
          "className": "Movie"
        }],
        [{
          "Image": {
            "__type": "File",
            "name": "tfss-65707002-e78b-47bd- 9c7a-da072f388e25-deliver.jpg",
            "url": "http://files.parsetfss.com/49a11e0f-0c84-417e-b81b-58f5e97abae9/tfss-65707002-e78b -47bd-9c7a-da072f388e25-deliver.jpg"
          },
          "Title": "Deliver Us From Evil",
          "featured_actors": "Eric Bana, Édgar Ramírez, Oliv ia Munn",
          "genre": "Crime, Horror, Thriller",
          "imdb_rating": 6.5,
          "plot_summary": "New York police officer Ralph Sarchie inves tigates a series of crimes. He joins forces with an unconventional priest, schooled in the rites of exorcism, to combat the possessions that are terrorizing their city.",
          "running_time_mins": 118,
          "trailer_video_link": "http://www.imdb.com/vide o/imdb/vi1746054425/?ref_=tt_ov_vi",
          "viewer_rating": "15",
          "objectId": "BoCM1zbOvh",
          "createdAt": "2014-08-25T14:27:24.331Z",
          "updatedAt": "2014-08-25T19:49:09.910Z",
          "__type": "Object",
          "className": "Movie"
        }, {
          "Image": {
            "__type": "File",
            "name": "tfss-772 aedb6-2767-4935-88f8-ae9280bc512b-expendables.jpg",
            "url": "http://files.parsetfss.com/49a11e0f-0c84-417e-b81b-58f5e97abae 9/tfss-772aedb6-2767-4935-88f8-ae9280bc512b-expendables.jpg"
          },
          "Title": "The Expendables 3",
          "featured_actors": " Sylvester Stallone, Jason Statham, Jet Li",
          "genre": "Action, Adventure, Thriller",
          "imdb_rating": 6.3,
          "plot_summary": "Barney augments  his team with new blood for a personal battle: to take down Conrad Stonebanks, the Expendables co-founder and notorious  arms trader who is hell bent on wiping out Barney and every single one of his associates.",
          "running_time_mins": 126,
          "tra iler_video_link": "http://www.imdb.com/rg/VIDEO_PLAY/LINK//video/imdb/vi1896197145/",
          "viewer_rating": "18",
          "objectId": "8cT kg769gM",
          "createdAt": "2014-08-16T21:32:28.318Z",
          "updatedAt": "2014-08-16T21:35:56.217Z",
          "__type": "Object",
          "className": "Mo vie"
        }]
      ]
    }
    var jsonArray = data.result;
    $.each(jsonArray, function(index, data) {
      //adds all this values fron the array ,only from and to
      //console.log(data[0]);
      //alert(data[0].Title);
      //console.log(data[0].Title);
      document.write("-->" + data[0].Title);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this serves your needs perfectly!

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

Is there a way to integrate personalized Javascript files within Bootstrap 4?

As I work on developing my own components of Bootstrap 4 for a dashboard site, I have run into a challenge. I need to include custom JS to be compiled with my Bootstrap 4 project, but I am facing limitations. Every time I try to include a module, I am unab ...

Switch out an item within a list of objects with a different item

I have a variable called this.rows that contains a collection of items. There is a real-time item being received from the server, which matches one of the items in the this.rows object collection. How can I replace an item with new values? Below is an ex ...

Exploring the Concept of Callbacks in JavaScript

What happens behind the scenes when a function is passed as a parameter in JavaScript and how does the engine recognize it as a callback? ...

Troubleshooting an Ajax request in Google Scripts with a '$' variable bug

I am trying to implement an AJAX Request using the ajax() method. I have created the functions below on scripts.google.com, but encountered the following error: function AjaxCall() { var arr = { City: 'Moscow', Age: 25 }; $.ajax({ u ...

What is the best way to emphasize a sentence that spans across multiple tags?

Suppose I have the following text: var str = "Hi, How are you"; If I want to highlight this entire sentence in the HTML below in one go instead of splitting it into an array. If my HTML looks like this: <div> Hi, <span>How are</span> y ...

React JS: The active text object in Fabric JS canvas becomes uneditable after attaching an event listener

After implementing event listeners for copy-paste, cut-paste, and movement functionalities in different directions, I encountered an issue when trying to edit the active text object on the canvas. I am utilizing the fabricjs-react module. Below is the cod ...

Why does the React input value keep its value when the modal is re-rendered, despite the state being updated correctly?

Take a look at this sandbox link for the code snippet: Sandbox Showcased below is a table structure: https://i.sstatic.net/3F3Mc.png By clicking on the 'edit' button, a modal window opens up as shown below allowing you to edit input fields (onC ...

Sending a variable between two separate ajax functions in different pages

I'm having some trouble sending the Rest_ID to another page and using it in an Ajax call to fetch data from a database. Everything seems to be working fine, but I can't seem to access the value of Rest_ID. Here is the JavaScript document for fet ...

Unfortunately, the input type number does not allow for the removal of decimal points

I need assistance with modifying the HTML code below. I want to remove the decimal point from the input field. Could anyone please provide instructions on how to accomplish this? <input type="number" min="0" step="1" ng-pattern="/^(0|[1-9][0-9]*)$/" ...

From transitioning from AngularJS to the latest version Angular 8

I have an Angular application where I need to update some old AngularJS code to work with Angular table.html <table ngFor="let group of vm.groups" style="float: left"> <thead> <tr> <th><b>Sl. No</b ...

Having trouble retrieving city data from the Geonames API with the specified city name

Greetings! I am currently in the process of developing a straightforward web application to retrieve city data from the geonames API. You can access the API via this URL: However, when I receive the data back, it appears as an empty array. Interestingly, ...

jQuery fails to locate class following AJAX reply

In my application, there is a cart feature where users can remove items from their cart, triggering a refresh of the contents using AJAX. However, I noticed that after removing an item from the cart, the response switches from asynchronous to synchronous m ...

Personalized data based on the language within Next.js

Is there a way to customize Metadata for users based on search engine keywords? To enhance SEO performance on my website, I am working on setting up unique Metadata for the two languages my website supports: English and Portuguese. Specifically, I aim to ...

How to retrieve the href ID in Node.js using app.js

I am facing an issue with sending parameters to the dashboard while using an href link. I want to include an identifier when clicking on the link that will be passed to the dashboard. The most straightforward solution would involve extracting the id or nam ...

The error message "TypeError: firebase.firestore() is not a function in web JavaScript" indicates

Currently, I am encountering an issue while attempting to upload an image on Firebase Cloud Storage using web Javascript. The error message "firebase.firestore() is not a function" is being displayed in my console. Do you think I might be going about this ...

Leveraging the power of Javascript and Firebase within the Angular framework

When attempting to integrate Firebase with Angular, I encountered an issue where my localhost was not able to function properly with my JavaScript code. The strange thing is that everything works fine when the code is placed directly in the index.html file ...

Is there a similar function in PHP to creating an array with a specified number of elements in JavaScript using "new Array(number)"?

While attempting to convert a basic Javascript function into PHP, I encountered a variable declared as var Variable = new Array (13). In PHP, variables are typically declared like this: $variable = array() But what does the "13" in new Array(13) signify? ...

Determining the worth of radio buttons, dropdown menus, and checkboxes

I am working on designing a menu for a pizza place as part of a learning project. The menu allows users to select their pizza size from small, medium, and large using radio buttons, and then customize it further with three select boxes where each selection ...

Having difficulty sending file input contents to controller action with jquery in ASP.Net Core 6.0

When attempting to send a file to a controller action for saving, I encountered two issues. The first problem arose when using $.post to submit the data: $("#setting-form").on("submit", function(event) { var formData = new FormData(); ...

Button click does not display Div

As a newcomer to programming, I apologize if my question seems trivial or if the code I provide is not flawless. My goal is to develop a basic web application in Flask that enables users to monitor their CO2 emissions by entering data about their daily con ...