-1

I have a JSON Object like this:

{
    "Items": [{
        "Name": "CATS",
        "Value": 5.0
    }, {
        "Name": "DOGS",
        "Value": 6.0
    }, {
        "Name": "FISH",
        "Value": 9.0
    }, {
        "Name": "CATS",
        "Value": 4.0
    }, {
        "Name": "DOGS",
        "Value": 2.0
    }, {
        "Name": "FISH",
        "Value": 3.0
    }]
}

As you can see, there are 2 of each key and I would like to reduce them to 1 and add all the values. So what I want to achieve is this:

{
    "Items": [{
        "Name": "CATS",
        "Value": 9.0
    }, {
        "Name": "DOGS",
        "Value": 8.0
    }, {
        "Name": "FISH",
        "Value": 12.0
    }]
}

What is the most efficient way to implement this?

Thanks!

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
The Cook
  • 1,403
  • 3
  • 17
  • 33
  • You may consider using a map in the language you are working on. The key of this map would be the item name and the value, would be the total. – Jeanderson Candido Jun 13 '16 at 20:06
  • The question is too general. I would split it into individual questions in the languages you want answers. –  Jun 13 '16 at 20:09
  • Start with [Parsing JSON in Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) because there is no "efficient" way other than to look at every element. – OneCricketeer Jun 13 '16 at 20:17
  • @cricket_007 I see you removed the [tag:swift] tag. Isn't it presumptuous to remove it? The author may want an answer in Swift so it should be up to the author to change that. –  Jun 13 '16 at 20:23
  • 1
    @ColGraff I don't think Swift coincides with the "Java/Android" tags, so therefore I removed it. Plus, cross-language tagging would make the question somewhat broad. – OneCricketeer Jun 13 '16 at 20:25
  • 1
    I agree that the tags were confusing and too broad but since we can't truly determine the author's intent the best we can do is encourage the author to respond or vote to close the question. –  Jun 13 '16 at 20:27
  • I am developing a cross platform app so I added both tags, didn't know that is against the rules. – The Cook Jun 14 '16 at 06:00
  • It's not against the rules but you're generally better off asking once for each language because you may get two completely valid answers in different languages. Then how do you choose which one to accept? Not to mention that tags which don't directly relate to each other causes confusion, you're less likely to get people to answer. –  Jun 16 '16 at 01:58

1 Answers1

1

you could create a new JSON array (let's call it arrayA) and start looping through the given array (let's call it arrayB).

Start looping through each element in arrayB and check for each element if it exists in arrayA. If it exists, add its value to the value of the element in arrayA which has the same key, else just add it to arrayA.

Omar El Halabi
  • 2,118
  • 1
  • 18
  • 26