-4

Below JSON Object needs to be iterated and need result as below.

[
  {"Aazam":1, "Jagannath":2, "Bharath Kumar M":4 },
  {"Bharath Kumar M":1, "Syad":1 },
  {"Bharath Kumar M":2 }
]

output needed (can be in map):

Aazam: 1
Jagannath: 2
Bharath Kumar M: 4, 1, 2
Syad: 1

I tried with ES 6 syntax, I am able to get key and values but I am not successful in forming the array as needed.

Solution should be generic.

ADyson
  • 57,178
  • 14
  • 51
  • 63
Squapl Recipes
  • 132
  • 3
  • 10
  • Please share the code you've tried – Dexygen Sep 04 '18 at 14:22
  • 3
    There's no JSON in your question or "code" – Andreas Sep 04 '18 at 14:22
  • it is a valid json actually – MKougiouris Sep 04 '18 at 14:23
  • if you've got some code you tried, then in order to fix it we will need to see it, please. And also give a clear description of what goes wrong with it current (errors, warnings, unexpected behaviour, that kind of thing). Thanks. – ADyson Sep 04 '18 at 14:24
  • 2
    @MKougiouris That's not JSON -> [javascript - What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Sep 04 '18 at 14:26
  • _I tried with ES 6 syntax, I am able to get key and values but I am not successful in forming the array as needed_.... Post what you've tried, please. – lealceldeiro Sep 04 '18 at 14:28
  • @Andreas jsonlint.com, json.parser.online.fr, ... it is JSON alright.. its just not in a string variable.. but the representation, if it were an actualy string, would be a json – MKougiouris Sep 04 '18 at 14:37
  • @Andreas put this in a fiddle var jstring= '[{"Aazam":1,"Jagannath":2,"Bharath Kumar M":4},{"Bharath Kumar M":1,"Syad":1},{"Bharath Kumar M":2}]'; var demo = JSON.parse(jstring) Its just a copy of his posted code, with added quotes to string it – MKougiouris Sep 04 '18 at 14:39
  • @MKougiouris Please check the link I've posted. There's a huge an distinctive difference between an object and a string representation of such an object, a.k.a JSON. – Andreas Sep 04 '18 at 14:40

1 Answers1

1

You can have a object as a output with the unique keys and values for each key as an array that holds the values of all similar keys.

var arr = [{
    "Aazam": 1,
    "Jagannath": 2,
    "Bharath Kumar M": 4
  },
  {
    "Bharath Kumar M": 1,
    "Syad": 1
  },
  {
    "Bharath Kumar M": 2
  }
];

var res = arr.reduce((acc, item) => {
  var keys = Object.keys(item);
  keys.forEach((key) => {
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(item[key]);
  });
  return acc;
}, {});
console.log(res);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62