0

I read this Sorting an array of JavaScript objects excellent post on how to sort the objects retrieved from Json. However, I couldn't find a way if I want to access particular element of the array. For example,

if we have this -:

var homes = [{
   "h_id": "3",
   "city": "Dallas",
   "state": "TX",
   "zip": "75201",
   "price": "162500"
}, {
   "h_id": "4",
   "city": "Bevery Hills",
   "state": "CA",
   "zip": "90210",
   "price": "319250"
}, {
   "h_id": "5",
   "city": "New York",
   "state": "NY",
   "zip": "00010",
   "price": "962500"
}];

In my array I have objects like

for (i to n)
var date = -----something----
var message = -----something----
    var homes=[{date,message}]

Now after sorting, if I wish to access date and store it somewhere, How will I do that?

Any help would be greatly appreciated.

Thanks

Community
  • 1
  • 1
SandBag_1996
  • 1,570
  • 3
  • 20
  • 50

1 Answers1

0

since your json is array of objects, you can push the object into array using array.push() method like the following :

homes.push({date:new Date(), message :"shreedhar"});

if you want to push the date and message into each object in your json, you can do so like following :

for( var i=0; i<homes.length;i++){
homes[i].message = "some msg";
homes[i].date = "some date";
}
console.log(homes);

now if you want to access the anything inside the json

homes[0].message; // gives you "some msg"
homes[0].date; // gives you "some date"
Shreedhar
  • 5,502
  • 3
  • 22
  • 27
  • Actually I have already done that. To store them in an array I have done the same as you mentioned, now if I want to access message shreedhar above, how will I do that? and the second part "for loop" that you mentioned. I dont want to do that, as I am implementing the sorting algorithm I mentioned in the links in my question – SandBag_1996 Aug 03 '12 at 17:50
  • @UnderDog i have edited my answer please have a look at it :) – Shreedhar Aug 03 '12 at 17:53
  • so you mean, if I use var homes=[{date,message}] and I can access them using homes[0].messsage – SandBag_1996 Aug 03 '12 at 17:53
  • yes var homes=[{date:"date",message:"msg"}], can be accessible lik homes[0].message //it will gives you msg. – Shreedhar Aug 03 '12 at 17:55
  • That will be awesome if it really works that way. Lemme try and get back to you. Is it possible to contact you (regarding the same) on the gmail_id you have mentioned on your profile link? – SandBag_1996 Aug 03 '12 at 17:59