簡體   English   中英

將對象數組分組並添加到復雜對象:Javascript

[英]Grouping and adding array of objects to a complex object: Javascript

我有一個復雜的對象,需要在其中添加一些對象數組(根據字段分組並添加)

兩者的格式如下所示

//This is the source object where I need to add the below "arr" based on grouping

let filterObj = {
      "feature": "test",
      "filter": {
                 "and": [
                          { "field": "field1","value": "1"}
                        ]
                }
};

//This array needs to be added to above object by grouping based on field
let obj = [
           {"field": "field1","value": "2"},
           {"field": "fiedl2","value": "3"},
           {"field" : "field2","value": "4"},
           {"field" : "field3","value" : "5"}
          ]

我希望輸出具有以下格式:

var result = {
              "feature": "test",
              "filter": {
                 "and": [
                          {
                           "or" : [
                                    {"field": "field1","value": "1"},
                                    {"field": "field1", "value": "2"}
                                  ]                      
                          },
                          {
                            "or" : [
                                     {"field": "field2","value": "3"},
                                     { "field": "field2","value": "4"},
                                   ]                      
                          },
                          {  "field": "field3", "value": "5"}
                  ]
              } 
}

// The method that I have tried

filterObj.filter.and.or(...obj) ;// Does not work 


我需要根據字段值將它們分組,然后將它們添加到對象的“或”數組(如果字段值相同)。 如果沒有,則將其直接添加到“和”對象數組中。

幫助將不勝感激。

  • CONCATfilter.andobj陣列在一起。
  • reduce結果數組。
  • 創建一個以每個field為鍵的累加器。
  • 如果鍵已經存在並具有or屬性,則將當前對象添加到or數組。
  • 如果鍵存在但不具有or屬性,請創建一個數組,該數組具有累加器中的現有對象和要迭代的當前對象。
  • 如果密鑰不存在,請添加密鑰並將其設置為當前對象。
  • 然后在結果對象上使用Object.values()獲取and數組。

 let filterObj={feature:"test",filter:{and:[{field:"field1",value:"1"}]}}, obj=[{field:"field1",value:"2"},{field:"field2",value:"3"},{field:"field2",value:"4"},{field:"field3",value:"5"}]; const merged = obj.concat(filterObj.filter.and || []).reduce((r, o) => { if(r[o.field] && r[o.field].or) r[o.field].or.push(o); else if(r[o.field]) r[o.field] = { or: [r[o.field], o] } else r[o.field] = o; return r; }, {}) const filter = { and: Object.values(merged) }, { feature } = filterObj; console.log({ feature, filter }) 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM