我想在使用javascript
制作的json数组中检索具有相同id的对象var Array = {
"1": {"text": "Number one", "time": "16 03 13"},
"1": {"text": "Number two", "time": "14 03 13"},
"1": {"text": "Number three", "time": "13 03 13"},
"2": {"text": "Number one", "time": "13 03 13"},
};
我试过这种方式,但显然它只显示了第一个结果(第一个)
var get = Array[1];
alert(get.text);
我想到了一个循环,我该怎么办?
答案 0 :(得分:8)
Array
用作变量名称。你需要这个:
var myArray = [
{"id" : 1, "text": "Number one", "time": "16 03 13"}, //index 0
{"id" : 1, "text": "Number two", "time": "14 03 13"}, //index 1
{"id" : 1, "text": "Number three", "time": "13 03 13"}, //index 2
{"id" : 2, "text": "Number one", "time": "13 03 13"} //index 3
];
var i;
for(i=0;i<myArray.length;i++){
if(myArray[i].id === 1){
console.log(myArray[i].text);
}
}
这是另一种方法,这需要重组您的数据。如果id为1的条目具有多个值,则可以在每个键下保留一个数组。
var myArray = {
"1" : [
{"text": "Number one", "time": "16 03 13"}, //index 0
{"text": "Number two", "time": "14 03 13"}, //index 1
{"text": "Number three", "time": "13 03 13"} //index 2
],
"2" : [
{"text": "Number one", "time": "13 03 13"} //index 0
]
};
var ones = myArray['1'];
for(i=0;i<ones.length;i++){
console.log(ones[i].text);
}
另一种方法是使用Array.prototype.filter
var myArray = [
{"id" : 1, "text": "Number one", "time": "16 03 13"}, //index 0
{"id" : 1, "text": "Number two", "time": "14 03 13"}, //index 1
{"id" : 1, "text": "Number three", "time": "13 03 13"}, //index 2
{"id" : 2, "text": "Number one", "time": "13 03 13"} //index 3
];
//create an array containing only those with id of 1
var filtered = myArray.filter(function(val,i,arr){
return val.id === 1;
});
for(i=0;i<filtered.length;i++){
console.log(filtered[i].text);
}