2017-02-27 38 views
-1

値(または親の値)に基づいて論理条件を満たすJSON/JavaScript ArrayまたはObjectでアイテムを見つける方法を教えてください。複雑な条件を満たすフィルタ/検索オブジェクト/配列アイテム

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! 
} 
:私は私の magicalWay機能が array.prototype.filterどのようにいくつかを使用しなければならないと思います

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関数を定義する)私がしようとしている


追加:MySQLのJSON抽出と同様、 '$ [*]。items' retすべての項目のitemsの値を1つの配列に納めてください!

+1

'true 'は' magicalWay() 'の2回目の呼び出しを意味します。達成したいことの詳細を追加する必要があります。 –

+0

パスパターンの各項目について「true」を評価すると、それらはすべて受け入れ可能です。@AmreshVenugopal – MohaMad

+0

私の理解によれば、2番目の引数に基づいて配列またはオブジェクト内の項目の値を求めますか? –

答えて

2

最初のステップは、あなたが望む結果を得るために使用したい実際機能を定義することです:あなたはあなたのobjectのために同じことを行う必要があります

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

を入力。あなたはどのよう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

関連する問題