[英]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
我需要根據字段值將它們分組,然后將它們添加到對象的“或”數組(如果字段值相同)。 如果沒有,則將其直接添加到“和”對象數組中。
幫助將不勝感激。
filter.and
和obj
陣列在一起。 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.