簡體   English   中英

篩選和搜索滿足復雜條件的對象/數組項目

[英]Filter and search Object/Array items that meet complex conditions

如何在JSON / JavaScript數組或對象中找到基於其值(或其父值)滿足邏輯條件的某些項目?

我要嘗試的內容(定義magicalWay函數!):

myArray = [
            {"type":"A","items":[0,1,2,3,4]},
            {"type":"B","items":['x','y','z']}
          ];

magicalWay(myArray,"<parent>.type=='A'","<this>.items");
//and output: [0,1,2,3,4]

magicalWay(myArray,"true","<this>.items");
//and output: [[0,1,2,3,4],['x','y','z']]

myObject = {
  "type": "A",
  "items": [
    {
      "type": "B",
      "items": ['x','y']
    },
    {
      "type": "C",
      "items": [0,1]
    }
  ]
};

magicalWay(myObject,"true","<this>.items[*].items");
//and output: [['x','y'],[0,1]]

任何建議都可以幫助我:)

我認為我的magicalWay函數必須使用array.prototype.filter一些方式:

function magicalWay(myVar,strCondition,strPattern){
  //replacing strCondition groups like [*] and others, and evaluate strCondition for each searching items.
  //strPattern is which path should be extract and search
  //and myVar is which searching through!
}

另外:就像MySQL JSON提取一樣,'$ [*]。items'將所有項目的items值返回到一個數組中!

第一步是定義要用於獲得所需結果的實際功能

 var myArray = [ { "type": "A", "items": [0, 1, 2, 3, 4] }, { "type": "B", "items": ['x', 'y', 'z'] } ]; var result1 = myArray .filter(obj => obj.type === "A") // Select .map(obj => obj.items) // Get nested .reduce((arr, cur) => arr.concat(cur), []); // Flatten //[0,1,2,3,4] console.log(JSON.stringify(result1)); 

您需要對object輸入執行相同的操作。 一旦弄清了如何filtermapreduce工作量,就可以使用以下簽名創建函數:

function getData(source, itemFilter, propertyGetter) { /* ... */ }

現在,如果需要從基於字符串的過濾器定義開始,則必須解析字符串並返回實際函數。 我認為您提出的字符串邏輯有些危險並且很難解析,但是如果您編寫嚴格的測試,您可能會不滿意它……出發點可能是:

 const noFilter = () => true; function getFilterMethod(str) { if (str === "true") { return noFilter; } const parts = str.split(".").slice(1); return ( obj => parts.reduce((cur, key) => cur[key], obj) ); } const data = [ { items: true }, { items: false }, { test: 1 } ]; console.log("true:", JSON.stringify(data.filter(getFilterMethod("true"))) ); console.log("<this>.items:", JSON.stringify(data.filter(getFilterMethod("<this>.items"))) ); 

結合兩者,添加數據獲取器邏輯,您將朝着類似的方向發展:

magicalWay(
  myArray, getFilterMethod("true"), getPropertyExtractor("<this>.items")
)

我不會為您編寫其余代碼,但是如果您有特定問題,我們很樂意為您提供幫助!

暫無
暫無

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

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