2011-06-07 14 views
6

मैं एक जेसन ऑब्जेक्ट सरणी फ़िल्टर करने के लिए grep का उपयोग करने की कोशिश कर रहा हूं ताकि सरणी की खोज की जा सके और यदि किसी भी कुंजी # 2-6 का मान हाँ है, तो कुंजी 1 और 7 का मान वापस कर दिया जाता है ।jquery grep json ऑब्जेक्ट सरणी पर

सरणी नीचे है - दूसरे शब्दों में, यदि 'स्थान' कुंजी के लिए मानों में से कोई भी हां है, तो नाम और विवरण सूची आइटम के रूप में वापस आते हैं।

किसी भी मदद की बहुत सराहना की जाती है।

[ 
    { 
     "name": "name", 
     "location1": "no", 
    "location2": "no", 
    "location3": "yes", 
    "location4": "no", 
    "location5": "no", 
    "description": "description of services" 
    }, 

    { 
    "name": "name", 
     "location1": "yes", 
    "location2": "no", 
    "location3": "yes", 
    "location4": "no", 
    "location5": "no", 
    "description": "description of services"   
    } 
] 

उत्तर

13

आप grep और map दोनों का उपयोग करने की आवश्यकता होगी। यदि a सरणी ऊपर वर्णित है (लेकिन name1, name2, आदि के साथ), तो बाद निम्नलिखित:

var b = $.grep(a, function(el, i) { 
    return el.location1.toLowerCase() === "yes" 
      || el.location2.toLowerCase() === "yes" 
      || el.location3.toLowerCase() === "yes" 
      || el.location4.toLowerCase() === "yes" 
      || el.location5.toLowerCase() === "yes"; 
}); 

var c = $.map(b, function(el, i) { 
    return { 
     name: el.name, 
     description: el.description 
    }; 
}); 

c शामिल होंगे [{"name":"name1","description":"description of services1"},{"name":"name2","description":"description of services2"}]

See example →

+0

वाह - धन्यवाद आप, धन्यवाद - यह वही है जो मैं ढूंढ रहा था - और मैंने नक्शा इस्तेमाल किया या पहले स्ट्रिंग किया। जेसन डेटा बाहरी फाइल से आ रहा है और मुझे बिल्कुल यकीन नहीं है कि इसे var var को कैसे असाइन किया जाए ...? – sharpiemarker1

+0

'$ .getJSON ('yourFile.json', फ़ंक्शन (डेटा) {// यहां डेटा आपके सरणी होगा});' – mVChr

+0

कमाल - धन्यवाद, धन्यवाद! – sharpiemarker1

1

मेरे संस्करण बहुत पिछले जवाब के समान है , मुझे उम्मीद है कि यह मदद करता है:

var checkYes = function(element) { 

     var isYesInside = false; 

     $.each(element, function(key, value) { 
      if (value == "yes") 
       isYesInside = true; 
     }); 

     return isYesInside; 
    }; 

    var yeses = $.grep(a, function(element, index) { 
     return checkYes(element); 
    }); 

    var finalArray = $.map(yeses, function(el, i) { 
     return { 
      name: el.name, 
      description: el.description 
     }; 
    }); 
संबंधित मुद्दे