-2

I have an array of objects like following:

[
  [{
    "field": "gender_code",
    "operator": "EQUALS",
    "value": "Male"
  }, {
    "field": "gender_code",
    "operator": "EQUALS",
    "value": "Female"
  }],
  [{
    "field": "encounter_facility",
    "operator": "EQUALS",
    "value": "BS&W Facility 126"
  }, {
    "field": "encounter_facility",
    "operator": "EQUALS",
    "value": "BS&W Facility 608"
  }]
]

I want the objects with same field value to form array of values like following:

  [
    [{
      "field": "gender_code",
      "operator": "EQUALS",
      "value": ["Male", "Female"]
    }],
    [{
      "field": "encounter_facility",
      "operator": "EQUALS",
      "value": ["BS&W Facility 126", "BS&W Facility 608"]
    }]
  ]
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    Welcome to Stack Overflow! Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output using the `[<>]` snippet editor. – mplungjan May 11 '20 at 09:02

1 Answers1

0

You can use map and reduce to achieve it.

let objects = [
  [{
    "field": "gender_code",
    "operator": "EQUALS",
    "value": "Male"
  }, {
    "field": "gender_code",
    "operator": "EQUALS",
    "value": "Female"
  }],
  [{
    "field": "encounter_facility",
    "operator": "EQUALS",
    "value": "BS&W Facility 126"
  }, {
    "field": "encounter_facility",
    "operator": "EQUALS",
    "value": "BS&W Facility 608"
  }]
];

objects = objects.map((items) => [
  items.reduce((carry, item) => {
    carry.value.push(item.value);
    return carry;
  }, {
    field: items[0].field,
    operator: items[0].operator,
    value: []
  })
]);

console.log(objects);
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50