2016-10-25 35 views
-1

goal 所以我和我的搭檔是那種糊塗的,我們希望如何顯示或列表具有來自陣列相同/相似的價值觀等名稱....如何列出由於相似數組而導致的JSON對象?

我們也想嘗試該隨機陣列正在「比較」 有沒有辦法做到這一點?

這裏的代碼,我到目前爲止:

的html代碼:

<body> 
<div id="message"></div> 
<div id="message2"></div> 
<div id="related"></div> 
</body> 

的Jquery:

$(document).ready(function(){ 

// Get JSON file 
$.ajax({ 
    type: 'GET', 
    url: 'scripts/data.json', 
    success: function(data) { 

     alert("hello"); 
     $.each(data, function(i, objects){ 
      $("#message").append(objects.name); 
      $("#message2").append(objects.thingYouWantToDo); 
     }); 
    }, 

}); 
for(var i = 0; i < objects.length; i++) 
{ 
if(objects[i].objects.thingYouWantToDo == 'Skydive') 
{ 
$("related").append(objects[i].objects.name); 
    } 
} 
}); 

JSON文件:

[ 
{ 
    "name": "Jim", 
    "iveNeverSinceIGotHere": "Went to a club", 
    "oneCoolPlaceIWantedCheckOut": "Cobo hall", 
    "favoritePets": "Dogs", 
    "favoriteColor": "Blue", 
    "age": 22, 
    "foreignWhereDidYouComeFrom": "I was born here", 
    "school": "College for Creative Studies", 
    "socialLinkFrom": "Instagram", 
    "shareASocialLink": "nahxiii", 
    "willingToMeetNewPeopleStrangers": "Yes" 
    "thingYouWantToDo": "Skydive" 
}, 
{ 
    "name": "Tommy ", 
    "oneCoolPlaceIWantedCheckOut": "Maldives", 
    "age": 24, 
    "foreignWhereDidYouComeFrom": "China ", 
    "school": "Wayne State University", 
    "socialLinkFrom": "Wechat ", 
    "shareASocialLink": "pillsi", 
    "willingToMeetNewPeopleStrangers": "Yes", 
    "thingYouWantToDo": "Skydive" 
} 
] 

現在我想列出4到所有具有「天空」的物體潛水「in」thingYouWantToDo「

任何建議/方法/或插件使用? 謝謝?

+0

這是值得嘗試自己先寫一些代碼。看看'lodash' - 這是一個有許多不同方法的圖書館,可以幫助你實現這一目標。 – James111

回答

0

使用underscore.js人,這裏是鏈接:http://underscorejs.org/

查詢:(使用_.filter(list, predicate, [context])_.where(list, properties)

var skydiveObjects = _.filter(objects, function(obj) { 
    return obj.thingYouWantToDo == "skydive"; 
}); 

var skydiveObjects = _.where(objects, {thingYouWantToDo: "skydive"}); 

_.map(skydiveObjects, function(obj) { 
    $("related").append(obj.name); 
}) 
相關問題