Peter Peter - 5 months ago 7
JSON Question

Trying to filter and combine JSON items

I have a JSON with several objects with this format:

[{
"id":14,
"friendlyName":"NameOfPlace 1",
"lat":30.402735,
"lon":-90,
"address":"1 place street",
"city":"NYC",
"state":"NY",
"zipCode":"12346",
"locationCode":"MQ00003",
"details":"in the bank"
},
{
"id":15,
"friendlyName":"NameOfPlace 2",
"lat":30.402735,
"lon":-90,
"address":"1 place street",
"city":"NYC",
"state":"NY",
"zipCode":"12346",
"locationCode":"MQ00003",
"details":"near ATM"
}]


They are locations of stores. I have several of these in a list. Some of them have names like Name 1 and Name 2, if there are 2 locations within the same building. I am trying to find a way to combine them into one object with both values but only one place ("Name" in the case of the example). I have two questions, if I have list of objects like above can I sort based off of
friendlyName
alphabetically then check to see if there are similar named locations that can be combined into one object. Note the locations will have the same lat long and address, just different details and ids. I can only figure out how todo it linearly and it is very slow for the mobile app I am trying to do.

Answer

You could use a hash table for the grouping of the friendly name and generate a new array with the data. If the data is different, all values are in an array included.

var data = [{ "id": 14, "friendlyName": "NameOfPlace 1", "lat": 30.402735, "lon": -90, "address": "1 place street", "city": "NYC", "state": "NY", "zipCode": "12346", "locationCode": "MQ00003", "details": "in the bank" }, { "id": 15, "friendlyName": "NameOfPlace 2", "lat": 30.402735, "lon": -90, "address": "1 place street", "city": "NYC", "state": "NY", "zipCode": "12346", "locationCode": "MQ00003", "details": "near ATM" }],
    grouped = [];

data.forEach(function (o) {
    var key = o.friendlyName.split(/(?= \d*$)/)[0];
    if (!this[key]) {
        this[key] = { Name: key };
        grouped.push(this[key]);
    }
    Object.keys(o).forEach(function (k) {
        if (!(k in this[key])) {
            this[key][k] = o[k];
            return;
        }
        if (this[key][k] === o[k]) {
            return true;
        }
        if (Array.isArray(this[key][k])) {
            this[key][k].push(o[k]);
            return;
        }
        this[key][k] = [this[key][k], o[k]];
    }, this);
}, Object.create(null));

console.log(grouped);