Eliminating Redundancies in Json Document with Javascript

Looking for assistance with parsing a JSON file (test.json) and removing duplicate "name" entries from the test array.

{
    "test": [{
            "name": "jeb",
            "occupation": "teacher"
        },

        {
            "name": "jeb",
            "occupation": "writer"
        },
        {
            "name": "bob",
            "occupation": "skydiver"
        }

    ]
}

Here is the code I have so far:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        var i;
        var test= myObj.test.length;

        for (i=0; i<=myObj.test.length; i++) {
          var name = myObj.test[i].name;
          var occupation = myObj.test[i].occupation;
          console.log(name + " and " + occupation)

        }
      }
}
xmlhttp.open("GET", "test.json", true);
xmlhttp.send();

The current output is:

jeb and teacher
jeb and writer
bob and skydiver

Desired output:

jeb and teacher, writer
bob and skydiver

Any help or suggestions would be greatly appreciated. Thank you!

Answer №1

To achieve the desired outcome, it is recommended to transform the data into an object where the key is the person's name and the value is an array of their occupations. After creating this object, you can easily loop through it and display each person's list of occupations:

const data = {
  "test": [{
    "name": "jeb",
    "occupation": "teacher"
  },{
    "name": "jeb",
    "occupation": "writer"
  },{
    "name": "bob",
    "occupation": "skydiver"
  }]
};

const occupationsByNames = data.test.reduce((acc, { name, occupation }) => {
  if (!acc[name]) acc[name] = [];
  acc[name].push(occupation);
  return acc;
}, {});
Object.entries(occupationsByNames).forEach(([name, occupations]) => {
  console.log(name + ' has occupations: ' + occupations.join(', '));
});

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

Retrieve a JSON object from a JSON array using a specific key

I am facing a situation where I have a json array containing multiple json objects. Let's take the example of a course object with the following structure: {"name": "Math", "unit": "3"} The json array looks something like this: [{"name": "Math", "u ...

Guide on conducting a JSR223 assertion test on a JSON array stored as a key's value within JMeter

Looking to conduct an assertion test on a JSON array presented in JMeter: { "item": [ { "id": "cx34ty1", "name": "xyzitem", "isSerialNoRequired": false, "itemPro ...

What is the best method for eliminating excessive spaces within a JSON file?

As a newcomer to json and node.js, I am faced with a json file that contains unnecessary spaces. How can I remove these spaces? .json file { "Product_Name": "Logitech M235 Wireless Mouse (Red)", "Brand": "Logitech", ...

exploring the contrast of css versus javascript selectors

Could you please explain the contrast between div#name and #name? Is there a significant difference when using class or id to position an element? Thank you for your help. ...

Tips for implementing the same autocomplete feature across multiple form fields

Struggling to add multiple products and provide auto-suggest for each product name? You're not alone. It seems like the auto suggest feature is only working for the first product. Can anyone point out what's going wrong here? Here's my HTML ...

Troubleshooting the challenge of saving multiple records using ajax in Django

Having trouble saving my form multiple times? I want users to be able to fill out the form with as many dimensions as needed. For example, if they enter two dimensions, I want to save each one as a separate record in the database. Any guidance on how to ac ...

Why does the Google Places API consistently provide latitude and longitude values under varying variables each time?

I am completely baffled by this situation. Initially, the API was returning the Latitude and Longitude like this: (I believe it was in this format): place.geometry.location.y as Latitude place.geometry.location.z as Longitude Then it suddenly change ...

Guide to running a Vue 3/Vite application in library mode for testing or demonstration needs

Currently, I am in the process of developing a Vue 3 components library and transforming it into an npm package using Vite.js. Following the guidelines provided in the official documentation, I have successfully configured Vite. However, I am faced with th ...

What is the best source for JSON serialization when using Ktor?

Having some trouble sending requests with Kotlin through Ktor. Android Studio doesn't seem to recognize the JSON serialization imports I'm trying to use. Here are the dependencies in my build.gradle.kts (:app): implementation("io.ktor:ktor- ...

OTCore initiates several pre-existing streams instead of just one

Apologies for any language issues as I am a native Dutch speaker. I have been using accelerator-core-js to share my screen and publish it. An example of this can be found here: https://github.com/opentok/accelerator-core-js. I attempted to implement it ...

Tips for resolving the problem when encountering the "undefined data" issue in the success callback of an AJAX request

I am facing an issue with my JSP page where I have a button that calls an Ajax method named "sendmail()" upon click. The send mail API is in the Controller, and I am trying to display an alert message in the Ajax success function using data.message, but it ...

parsing a SQL-stored array

After successfully serializing my arrays, I am facing challenges with unserializing and outputting them back into arrayed data. while( $row= $stmt->fetch(PDO::FETCH_ASSOC)) var_dump($row); { $rss=unserialize($row); echo $rss; } var_dump($rss); I ha ...

Determine the variance by subtracting the number provided by the user

I'm facing an issue with my JavaScript code and I can't seem to figure out why it's not working. This should be straightforward for someone with experience in JavaScript, but unfortunately, that's not the case for me. <!doctype html ...

Using ReactJS to trigger a timer function on a button click

Kindly Note: This is a unique query and not related to ReactJS - Need to click twice to set State and run function. The suggested solution there does not resolve my issue. This represents my original state: constructor(props) { super(props) this. ...

Error: Functionality cannot be achieved

Looking for assistance in resolving this issue. Currently, I am attempting to register a new user and need to verify if the username already exists or not. Below is the factory code used for this purpose: .factory('accountService', function($res ...

Extract the entire div including all its elements and then transmit it using the PHP mail function

Currently, I am developing a feature that allows users to send an email. The email should include only one div from the page which contains elements added using the jQuery drag and clone function. I am unsure how to copy the entire div along with its child ...

show a variable called - Random

Hey there, I've been struggling with a bug and despite multiple attempts, I can't seem to find a solution :( I want a month to be displayed when clicked, and then on another click, a different month should appear without repeating the previous ...

How can I update an image source using JavaScript in a Django project?

Is it possible to dynamically change the image src using onclick without relying on hard paths or Django template tags? I have concerns that this may not be best practice. How can I implement a method to inject/change the ""{% static 'indv_proj&b ...

The functionality of sending buttons on Whatsapp web using JavaScript seems to be not functioning

My code is not sending buttons for some reason, even though I have searched online for a solution with no luck. Here's the snippet: const { Client, LocalAuth ,MessageMedia, Buttons } = require('whatsapp-web.js'); const client = new Client( ...

Getting a Cookie in React from an Express JS API (MERN Stack)

My API in Express JS stores a token in a cookie on the client-side (React). The cookie is generated only when a user logs into the site. When testing the login API with Postman, the cookie is generated as expected: https://i.sstatic.net/rL6Aa.png However ...