2

I have a data like this:

[{
    "Key":"A",
    "Data":"1"  
},
{
    "Key":"B",
    "Data":"2"  
},
{
    "Key":"C",
    "Data":"12" 
},
{
    "Key":"A",
    "Data":"6"  
},
{
    "Key":"B",
    "Data":"4"  
}]

Output I want is:

[
    {
        "Key":"A",
        "Value":[{"Data":"1"},{"Data":"6"}]
    },
    {
        "Key":"B",
        "Value":[{"Data":"2"},{"Data":"4"}]
    },
    {
        "Key":"C",
        "Value":[{"Data":"12"}]
    }
]

I want the output like this in Javascript or TypeScript dynamically as I get this json data dynamic .

Can Someone Please help.

Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
Ayoush Kohli
  • 35
  • 1
  • 6
  • Gona have to iterate over your original array and build a new one by comparison. Stackoverflow can help you when you try that and run into issues. Stackoverflow wont write code for you though :) – Dominik Jul 28 '17 at 07:49

2 Answers2

2

You could use a hash table and group the items by Key property.

If the group does not exist, create a new group with key and Values array. Ten puth the new object to the result array. Later push the actual value to the Values array.

var data = [{ Key: "A", Data: "1" }, { Key: "B", Data: "2" }, { Key: "C", Data: "12" }, { Key: "A", Data: "6" }, { Key: "B", Data: "4" }],
    hash = Object.create(null),
    result = data. reduce(function (r, o) {
        if (!hash[o.Key]) {
            hash[o.Key] = { Key: o.Key, Value: [] };
            r.push(hash[o.Key]);
        }
        hash[o.Key].Value.push({ Data: o.Data });
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

you can do this:

let data = [{
    "Key":"A",
    "Data":"1"  
},
{
    "Key":"B",
    "Data":"2"  
},
{
    "Key":"C",
    "Data":"12" 
},
{
    "Key":"A",
    "Data":"6"  
},
{
    "Key":"B",
    "Data":"4"  
}];

let groupedData = data.reduce((results, item) => {
    results[item.Key] = results[item.Key] || [];
    results[item.Key].push(item.Data);

    return results;
}, {});

console.log(groupedData);
Jay
  • 841
  • 1
  • 8
  • 19