-1

This is my JSON object and I need to check for a particular id and get the date

 [
        {
          "id": "9b3b835b",
          "date": "Tue Mar 27 10:23:18 UTC 2018"
        },
        {
          "id": "57eab193",
          "date": "Thu Mar 29 14:45:23 UTC 2018"
        },
        {
          "id": "440f0cd9",
          "date": "Thu Mar 29 15:12:00 UTC 2018"
        },
 ]
Joshua
  • 3,055
  • 3
  • 22
  • 37
Ramana
  • 13
  • 2
  • 2
    You have an *array* there, not an object. `arr.find(obj => obj.id === id).date;` (well, technically an array is an object, but if you're dealing with an array, you should call it an array instead) – CertainPerformance Apr 12 '18 at 02:46
  • @CertainPerformance This will cause TypeErrors if the find method doesnt find anything (just a word of caution to the uneducated reader) – Abid Hasan Apr 12 '18 at 02:49
  • You should at least post what have you tried, or even searching, before making a question – iagowp Apr 12 '18 at 03:00

2 Answers2

1

yourVariable = [{
    "id": "9b3b835b",
    "date": "Tue Mar 27 10:23:18 UTC 2018"
  },
  {
    "id": "57eab193",
    "date": "Thu Mar 29 14:45:23 UTC 2018"
  },
  {
    "id": "440f0cd9",
    "date": "Thu Mar 29 15:12:00 UTC 2018"
  },
];

for (keys in yourVariable) {
  // supposing id your are looking for is 57eab193
  if (yourVariable[keys].id == '57eab193') {
    console.log(yourVariable[keys].date)
  }
}
bhansa
  • 7,282
  • 3
  • 30
  • 55
arun
  • 92
  • 1
  • 3
0
  • You can use the function find to get a specific according to a condition.

This alternative uses the logical operator || just to avoid access error over an undefined value.

var array = [{
    "id": "9b3b835b",
    "date": "Tue Mar 27 10:23:18 UTC 2018"
  },
  {
    "id": "57eab193",
    "date": "Thu Mar 29 14:45:23 UTC 2018"
  },
  {
    "id": "440f0cd9",
    "date": "Thu Mar 29 15:12:00 UTC 2018"
  },
];

var date = (array.find(o => o.id === "440f0cd9") || {}).date;
console.log(date);

date = (array.find(o => o.id === "ele") || {}).date;
console.log(date);
Ele
  • 33,468
  • 7
  • 37
  • 75