Alberto
Alberto

Reputation: 33

Retrive objects with the same id in json array (javascript)

I would like to retrive objects with the same id in my json array made with javascript

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"},
};

I tried in this way, but obviously it shows me only the first result (Number one)

var get = Array[1]; 
alert(get.text);

I thought about a loop, What can I do?

Upvotes: 0

Views: 4482

Answers (1)

Joseph
Joseph

Reputation: 119867

  • Do not use Array as a variable name.
  • Object keys cannot be duplicate. If you do, only the latest entry is fed to that key. The others are discarded. In your case, only the third "1" is accessible via the "1" key.
  • What you need is an array, not an object

You need this:

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

Here's another approach, and this requires restructuring your data. If your entry with id of 1 has multiple values, you could hold an array under each key.

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

Another approach is the use of 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);
}

Upvotes: 8

Related Questions