Dissecting Distinct and Alphabetized Attributes in JSON/JavaScript

Below is a code snippet that retrieves and organizes a list of values from JSON data in alphanumeric order based on a specific key-value pair:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {

  if (this.readyState == 4 && this.status == 200) {
    var myObjjj = JSON.parse(this.responseText);

    var result = myObjjj.features.filter(c => c.properties.AREAID === "area4").map(res => res.properties.CDNAME + "<br>").sort().join('');
    document.getElementById("list").innerHTML = result;
  }
};
xmlhttp.open("GET", "https://api.npoint.io/eed1932ca3c208946d86", true);
xmlhttp.send();
<html>
<head>
    <title>Read data from External JSON file using JavaScript</title>
</head>
<body>
    <h3>
        Data extracted from External JSON file using JavaScript.
    </h3>
    
        <p id="list" style="border: 2px solid yellow;"></p>
    

</body>
</html>

The JSON data retrieved from the specified URL contains information about different divisions and areas. The objective is to eliminate duplicate values to display only distinct entries, as shown below:

Area No. 13

Center No. 14

Division No. 11

Division No. 13

Division No. 14

Division No. 16

Division No. 17

Division No. 18

Division No. 19

Answer №1

Your code before optimization:

var result = myObjjj.features.filter(c => c.properties.AREAID === "area4").map(res => res.properties.CDNAME + "<br>").sort().join('');

Prior to the .join() operation, duplicates must be handled. Additionally, using .map() to insert <br> is unnecessary as .join() performs this function.

The snippet below utilizes new Set() and Array.from() for duplicate management:

const cdNames = myObjjj.features.filter(
  c => c.properties.AREAID === "area4"
).map(
  res => res.properties.CDNAME
);
const results = Array.from(new Set(cdNames)).sort().join('<br>');
  1. Filter by AREAID
  2. Convert the filtered array to an array of only CDNAMEs.
  3. Transform that array into a set. (Duplicates are eliminated as sets are unordered collections of distinct values. Re-adding an existing value in a set does not impact it.)
  4. Revert the set back to an array.
  5. Sort the array.
  6. Merge the array, with <br> serving as the separator.

Functional demonstration:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    const myObjjj = JSON.parse(this.responseText);

    const cdNames = myObjjj.features.filter(
      c => c.properties.AREAID === 'area4'
    ).map(
      res => res.properties.CDNAME
    );
    const results = Array.from(new Set(cdNames)).sort().join('<br>');

    document.getElementById("list").innerHTML = results;
  }
};
xmlhttp.open("GET", "https://api.npoint.io/eed1932ca3c208946d86", true);
xmlhttp.send();
<html>
<head>
    <title>Fetch data from External JSON file using JavaScript</title>
</head>
<body>
    <h3>
        Data extracted from External JSON file utilizing JavaScript.
    </h3>
        <p id="list" style="border: 2px solid yellow;"></p>
</body>
</html>

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

Does Google's web crawler have the ability to index content created by javascript?

Our web app generates content using javascript. Can Google index these pages? In our research on this issue, we primarily found solutions on older pages suggesting the use of "#!" in links. Within our app, the links are structured as follows: domain.co ...

What are some ways to retrieve data from a JSON response that is nested within an array, which in turn is nested within

click here for image description API Response:- { "hotelogix": { "version": "1.0", "datetime": "2017-01-17T11:37:58", "response": { "status": { "code": 0, "message": "success" }, "nightAuditDate": "2015-04-1 ...

How can we use the Selenium JavascriptExecutor in Java to return an Object from JavaScript?

I've encountered an issue while running a JavaScript file using Java with Selenium in my application. When I execute the JavaScript file with JavascriptExecutor after logging in, I'm only getting a null return instead of a valid one. Below is a ...

Prevent selection duplication in adjacent select by disabling the option in AngularJS ng-options

In my table, I have 2 select options that change dynamically. <tr> <th>Start time</th> <th>End time</th> </tr> <tr ng-repeat="s in config.time"> <td> <select ng-model="s.start_time" ...

Can we extract unique values from a JSONObject in Java?

I have a JSON file containing 500,000 objects in the following format: "WORKORDER": [ { "Attributes": { "SITEID": { "content": "BEDFORD" }, " ...

Parsing intricate JSON into Java with classes nested at various levels of depth

I am facing an issue with deserializing the nested JSON output from Cucumber into a single Java object. The JSON contains objects that are nested four levels deep, and I am currently using Jackson for deserialization but open to other solutions. Below is a ...

Issue with custom fonts not showing in PDFs when using Puppeteer, even though they are displayed in screenshots

I've been working on dynamically creating PDF files using the puppeteer library, but I'm facing an issue where the generated PDF doesn't display the custom fonts (.woff) that I have specified. Instead, it defaults to using the system font, T ...

Organize tabs with ease in the bootstrap-tabdrop plugin

My webpage features a navigation bar along with the bootstrap-tabdrop plugin, which places tabs in a dropdown menu if there are too many to display on one line. The main objective is: No action when navigating through currently displayed tabs. Clicking o ...

Send properties to the makeStyles function and apply them in the CSS shorthand property of Material UI

When working with a button component, I pass props to customize its appearance: const StoreButton = ({ storeColor }) => { const borderBottom = `solid 3px ${storeColor}`; const classes = useStyles({ borderBottom }); return ( <Button varian ...

What are the steps to globalize the ng-bootstrap datepicker?

For my current project, I am utilizing the ng-bootstrap datePicker component. The demo for my simple datePicker widget can be found here. However, I am now seeking to internationalize it by setting it to use the Russian language. Any assistance with this ...

Utilizing phonegap/jQueryMobile to extract OpenCart products in JSON format is a simple process

Looking to retrieve the product catalog in JSON format from my OpenCart store through a phonegap mobile application using Ajax, JavaScript/jQuery. Is this something that can be done with OpenCart? Any suggestions, ideas, or sample code would be greatly ap ...

Add a SlideUp effect to the .removeClass function by using a transition

Looking to incorporate a SlideUp transition while removing the class with .removeClass. This script handles showing/hiding the navigation menu based on page scroll up or down. I am looking to add a transition effect when the navigation menu hides. Check ou ...

Arranging a roster of models in C#

After developing a basic webapi2 program that returns JSON data, I encountered an issue with the order of child elements under their respective parents. Specifically, I need to rearrange the JSON structure so that certain MenuIds are placed under their cor ...

bind a class property dynamically in real-time

I need to dynamically generate a TypeScript class and then add a property to it on the go. The property could be of any type like a function, Promise, etc., and should use this with the intention that it refers to the class itself. let MyClass = class{ ...

What is the best way to execute synchronous calls in React.js?

Currently, I am a novice in working with React JS and I have been tasked with implementing a feature to reset table data in one of our UI projects. Here is the current functionality: There is a save button that saves all overrides (changes made to the or ...

There are various iterations of html2canvas available

After upgrading html2canvas from v0.5.0 to v1.0.0, a specific function ceased to work on iOS. Therefore, I am interested in utilizing v0.5.0 on iOS and v1.0.0 on other devices. Is there a way to incorporate and switch between both versions of html2canvas ...

Implementing date values in Rest API parameter with Azure Data factory

One of the parameters in my API Url is TIMESTAMP, with a specific value like: Actual Url: The timestamp value could expire, so I've created a parameter TS with the value utcNow() to prevent that. Now, my URL looks like: I'm using this updated ...

Executing JavaScript code in the Selenium IDE

I'm having trouble figuring out how to execute JavaScript within the Selenium IDE. The objective is to enter text into an input field, with a backend setup that verifies the current time in the input field for testing purposes: Here's the input f ...

Unable to add an event while looping through a NodeList in JavaScript

Seeking assistance in iterating a NodeList object using javascript, and implementing a click event for each item : document.addEventListener("DOMContentLoaded", async () => { try { posts.map(post => { container.innerHTML += out ...

Troubleshooting the issue with a styled subcomponent in React using Styled Components

Recently, I've delved into React and have been experimenting with creating a Modal component using styled components. My goal is to achieve a similar effect to Framer Motion's motion.div, but utilizing styled components instead. Currently, I hav ...