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.

1
  • 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 :) Commented Jul 28, 2017 at 7:49

2 Answers 2

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; }

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

1 Comment

Thanks Nina for your Help.
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.