I am working with JSON that is something like as follows in Javascript:
{
"data": [
{
"id": 1,
"name": "Data Point Zeta",
"unit": "456456456",
},
{
"id": 1,
"name": "Data Point Alpha",
"unit": "345345",
},
{
"id": 1,
"name": "Data Point Maverick",
"unit": "453455",
},
{
"id": 1,
"name": "Data Point Delta",
"unit": 3534545"",
},
{
"id": 1,
"name": "Data Point Delta",
"unit": 3534545"",
},
{
"id": 1,
"name": "Data Point Bravo",
"unit": "534553455",
},
{
"id": 1,
"name": "Data Point Bravo",
"unit": "534553455",
},
{
"id": 1,
"name": "Data Point Bravo",
"unit": "4356346436",
}
]
}
I want to be able to make this JSON unique via the name value, so for example I want to be able to parse the and change the JSON so it becomes like this:
{
"data": [
{
"id": 1,
"name": "Data Point Zeta",
"unit": "456456456",
},
{
"id": 1,
"name": "Data Point Alpha",
"unit": "345345",
},
{
"id": 1,
"name": "Data Point Maverick",
"unit": "453455",
},
{
"id": 1,
"name": "Data Point Delta",
"unit": 3534545"",
},
{
"id": 1,
"name": "Data Point Bravo",
"unit": "453455",
},
]
}
So I am retrieving the first unique instance of an object based on its name. I need to do so using basic Javascript, I can't use JQuery or any other libraries. And I don't want to have to sort the array.
I have already tried following code from the following questions but with no luck:
How to make a JSON array unique
Get unique results from JSON array using jQuery
The closest I got was using the following code:
var results = [];
for (var i = 0; i < myJSONArr.length; i++) {
if (myJSONArr[i + 1].name != myJSONArr[i].name) {
results.push(myJSONArr[i]);
}
}
But this always gives me an undefined error and if I put in code to check for the undefined error it leaves one from the list out. So for example it gets the following names:
Data Point Zeta
Data Point Alpha
Data Point Maverick
Data Point Delta
So Data Point Bravo never gets pushed to the array.
Can anyone point me in the direction of the proper way to achieve this?