如果某些字段在javascript中的对象数组中重复,则创建值数组[重复]

我有如下对象的数组:

[
  [{
    "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"
  }]
]

我希望具有相同字段值的对象形成值数组,如下所示:

  [
    [{
      "field": "gender_code",
      "operator": "EQUALS",
      "value": ["Male", "Female"]
    }],
    [{
      "field": "encounter_facility",
      "operator": "EQUALS",
      "value": ["BS&W Facility 126", "BS&W Facility 608"]
    }]
  ]
评论
  • _樱花巷
    _樱花巷 回复

    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.field = item.field;
        carry.operator = item.operator;
        carry.value = (carry.value || []).concat([item.value]);
        
        return carry;
      }, {})
    ]);
    
    console.log(objects);