0

I have a json file like below (test.json). I am unsuccessfully trying to parse the test array and remove duplicates of any "name" below

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

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

    ]
}

So far, my code is the following:

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();

and it prints out:

jeb and teacher
jeb and writer
bob and skydiver

I would like the end result to be be:

jeb and teacher, writer
bob and skydiver

Any help is appreciated. Thank you!

1 Answer 1

3

It would probably be best to reduce into an object indexed by name, whose value is an array of occupations, and then once the object is created, you can iterate over it and print the occupations of each name:

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

const namesByOccupation = obj.test.reduce((a, { name, occupation }) => {
  if (!a[name]) a[name] = [];
  a[name].push(occupation);
  return a;
}, {});
Object.entries(namesByOccupation).forEach(([name, occupations]) => {
  console.log(name + ' and ' + occupations.join(', '));
});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.