javascript - 检索 json 数组中具有相同 id 的对象 (javascript)

标签 javascript arrays json

我想在用 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);

我想到了一个循环,我能做什么?

最佳答案

  • 请勿使用Array 作为变量名称。
  • 对象键不能重复。如果这样做,则只有最新条目才会输入到该键中。其他的都被丢弃。在您的情况下,只能通过“1”键访问第三个“1”。
  • 你需要的是一个数组,而不是一个对象

你需要这个:

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

关于javascript - 检索 json 数组中具有相同 id 的对象 (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15448498/

相关文章:

c - 数组静态分配

java - 如何通过Cucumber从多个json文件中获取数据进行验证?

json - 如何在Elasticsearch中按日期范围正确过滤条目?

javascript - 为什么当版本正确时 Yarn 说 "Found incompatible module"?

javascript - 如何重命名/保留回调方法

javascript - 如何在纯 JavaScript 中发送二进制数据?

javascript - 网格中的 Page_validators 用于客户端验证

arrays - 二色图像压缩算法

javascript - 使用javascript在特定图像后插入文本

java - 将 SOAP 响应转换为 JSONArray