簡體   English   中英

如何在多個條件下過濾嵌套的對象數組?

[英]How do I filter nested array of objects on multiple conditions?

下面是對象的示例數組。 我希望根據criteriaTypeidsource過濾這個。 如果input.source匹配,則應過濾掉父對象。 此外,所有過濾條件都是可選的。

[{
    "id": "9be6c6299cca48f597fe71bc99c37b2f",
    "caption": "caption1",
    "criteriaType": "type2",
    "input": [
        {
            "id_1": "66be4486ffd3431eb60e6ea6326158fe",
            "criteriaId": "9be6c6299cca48f597fe71bc99c37b2f",
            "source": "type1",
        },
        {
            "id_1": "1ecdf410b3314865be2b52ca9b4c8539",
            "criteriaId": "9be6c6299cca48f597fe71bc99c37b2f",
            "source": "type2",
        }
    ]
},
{
    "id": "b83b3f081a7b45e087183740b12faf3a",
    "caption": "caption1",
    "criteriaType": "type1",
    "input": [
        {
            "id_1": "f46da7ffa859425e922bdbb701cfcf88",
            "criteriaId": "b83b3f081a7b45e087183740b12faf3a",
            "source": "type3",
        },
        {
            "id_1": "abb87219db254d108a1e0f774f88dfb6",
            "criteriaId": "b83b3f081a7b45e087183740b12faf3a",
            "source": "type1",
        }
    ]
},
{
    "id": "fe5b071a2d8a4a9da61bbd81b9271e31",
    "caption": "caption1",
    "criteriaType": "type1",
    "input": [
        {
            "id_1": "7ea1b85e4dbc44e8b37d1110b565a081",
            "criteriaId": "fe5b071a2d8a4a9da61bbd81b9271e31",
            "source": "type3",
        },
        {
            "id_1": "c5f943b61f674265b8237bb560cbed03",
            "criteriaId": "fe5b071a2d8a4a9da61bbd81b9271e31",
            "source": "type3",
        }
    ]
}]

我只能通過criteriaTypeid實現過濾。 但是我也無法按source過濾以確保在沒有input.source匹配的情況下不返回父級。

var json = <<array of objects>> ;
const {objectId: id, ctype: criteriaType, inputSource: source } = param; // getting the the params
json = ctype ? json.filter(({criteriaType}) => criteriaType === ctype ): json;
json = (objectId ? json.filter(({id}) => id === objectId ): json)
       .map (({id, caption, criteriaType, input }) => {
         //some manipulation 
         return { //results after manipulation}
       })

幫幫我! 提前致謝。 我不確定我們是否可以鏈接過濾器來實現它。

尋找與esLint兼容的代碼

有幾種方法可以解決這個問題。 你可以在純JS中實現這個,我推薦Lodash

1)Lodash 過濾器

``` javascript
var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];

_.filter(users, function(o) { return !o.active; });
// => objects for ['fred']

// The `_.matches` iteratee shorthand.
_.filter(users, { 'age': 36, 'active': true });
// => objects for ['barney']

// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']

// The `_.property` iteratee shorthand.
_.filter(users, 'active');
// => objects for ['barney']
```

2)JavaScript ES5 過濾器()

``` javascript
var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

var result = words
  .filter(word => word.length > 6)
  .filter(word => word.length < 8);

console.log(result);
// expected output: Array ["present"]
```

2) MapReduce

MapReduce是我最喜歡使用集合/集合的工具之一。

您在上面的代碼中使用了map() 訣竅可能是將map更改為reduce

使用map ,您可以獲得1-1的收集項目比例。

使用reduce ,您可以為輸入中的每個項目生成任意數量的項目。 例如

``` javascript
var stuff = ['couch', 'chair', 'desk'];

var hasFiveLetters = stuff.reduce((total, item) => {
  if (item.length === 5) total.push(item);  // add to total any items you like
  return total;  // don't forget to return total!
}, []);  // initialize total to []

console.log(hasFiveLetters); // ['couch', 'chair'];

```

要求是過濾器是可選的,並且不會返回任何源匹配的父項https://jsfiddle.net/cpk18dt4/9/

評論在代碼中。 希望它能解釋這個功能的作用。

const fnFilter = (criteriaType, id, source) => {
  let result = oData;

  if (criteriaType) { // it can be null (optional)
    result = result.filter(d => d.criteriaType === criteriaType);
  }
  if (id) { // it can be null (optional)
    result = result.filter(d => d.id === id);
  }
  if (source) { // it can be null (optional)
    result = result.filter(d => {
      const inputs = d.input.filter(inp => inp.source === source);

      // If none of the input.source match, the parent object should be filtered out
      if (inputs.length === 0) {
        return false;
      }
      d.input = inputs;
      return true;
    });
  }

  return result;
};

可以使用Lodash查找和過濾器。 與需要匹配的第一次匹配的Filter相比,在嵌套數組中查找會更快。

json = ctype ? _.filter(json, function(o) {
    return o.criteriaType === ctype;
}) || json;
json = objectId ? _.filter(json, function(o) {
    return o.id === objectId;
}) || json;
json = source ? _.filter(json, function(o) {
    return _.find(o.input, function(input_object) {
        return input_object.source === source;
    });
}) || json;

嘗試這個:

  var obj = [{ "id": "9be6c6299cca48f597fe71bc99c37b2f", "caption": "caption1", "criteriaType": "type2", "input": [ { "id_1": "66be4486ffd3431eb60e6ea6326158fe", "criteriaId": "9be6c6299cca48f597fe71bc99c37b2f", "source": "type1", }, { "id_1": "1ecdf410b3314865be2b52ca9b4c8539", "criteriaId": "9be6c6299cca48f597fe71bc99c37b2f", "source": "type2", } ] }, { "id": "b83b3f081a7b45e087183740b12faf3a", "caption": "caption1", "criteriaType": "type1", "input": [ { "id_1": "f46da7ffa859425e922bdbb701cfcf88", "criteriaId": "b83b3f081a7b45e087183740b12faf3a", "source": "type3", }, { "id_1": "abb87219db254d108a1e0f774f88dfb6", "criteriaId": "b83b3f081a7b45e087183740b12faf3a", "source": "type1", } ] }, { "id": "fe5b071a2d8a4a9da61bbd81b9271e31", "caption": "caption1", "criteriaType": "type1", "input": [ { "id_1": "7ea1b85e4dbc44e8b37d1110b565a081", "criteriaId": "fe5b071a2d8a4a9da61bbd81b9271e31", "source": "type3", }, { "id_1": "c5f943b61f674265b8237bb560cbed03", "criteriaId": "fe5b071a2d8a4a9da61bbd81b9271e31", "source": "type3", } ] }]; function filterObj(obj, column, value){ var newArray = obj.filter(function (el) { if(el[column]){ return el[column] == value; }else{ for(var key in el.input){ if(typeof(el.input[key] == "object")){ var item = el.input[key]; if(item[column] == value){return item;} } } } }); return newArray; } console.log(filterObj(obj, 'caption','caption1')); console.log(filterObj(obj, 'criteriaId','fe5b071a2d8a4a9da61bbd81b9271e31')); console.log(filterObj(obj, 'id_1','1ecdf410b3314865be2b52ca9b4c8539')); 

// if field has a value, filter on it, else return original json
const having = (json, field, val) =>
  val ? json.filter(j => j[field] === val) : json

const filterBySource = (json, source) => {
  if (!source) return json
  return json.filter(
    j => j.input.length > 0 && j.input.some(input => input.source === source)
  )
}

function search(json, params = {}) {
  const { objectId: id, ctype: criteriaType, inputSource: source } = params

  // if no filters, return the whole json
  if (!(id || criteriaType || source)) return json

  let result
  result = having(json, 'id', id)
  result = having(result, 'criteriaType', criteriaType)

  return filterBySource(result, source)
}

const params = {
  objectId: 'fe5b071a2d8a4a9da61bbd81b9271e31',
  ctype: 'type1',
  inputSource: 'type3'
}

search(json, params).map(({ id, caption, criteriaType, input }) => {
  // do something with filtered json
})

暫無
暫無

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

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