2017-02-27 89 views
-1

如何根據JSON/JavaScript Array或Object的值(或它們的父值)滿足邏輯條件?篩選和搜索符合複雜條件的對象/數組項目

什麼我想(定義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'ret將所有項目的items值都放在一個數組中!

+1

'true'對於'magicicalWay()'的第二次調用意味着什麼。您需要添加更多關於您想要實現的細節。 –

+0

評估路徑模式中的每個項目的「真」意味着它們都可以接受@AmreshVenugopal – MohaMad

+0

所以根據我的理解,您想要基於第二個參數的數組或對象內的項目的值? –

回答

2

的第一步是定義實際功能你會用它來得到你想要的結果:

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") 
) 

我不會爲你寫的代碼的其餘部分,但如果你有具體的問題我我很樂意幫忙!

+0

謝謝你的好回答。如果我有嚴重的問題,我會再問一次:D @ user3297191 – MohaMad