5

Given this object:

: http://www.w3.org/2005/Atom
gd: http://schemas.google.com/g/2005 
openSearch: http://a9.com/-/spec/opensearch/1.1/ 
app: http://www.w3.org/2007/app; 
media: http://search.yahoo.com/mrss/

How do I get the value of the first property? I suspect this is an easy process, but I'm drawing a blank. Thanks in advance.

The object is built as such:

Server side (php):

$namespaces = $feedXML->getNamespaces(true);
$arr = array(
'Status' => 'Success',
'Message' => 'Feed fetched.',
'Namespaces' => $namespaces,
'Feed XML' => $feedXML
);
echo json_encode($arr);

Client side (JS):

   var output = '';
    for (property in dataj["Namespaces"]) {
        output += property + ': ' + dataj["Namespaces"][property] + '; ';
    }
    alert(output);

I would like to be able to check the namespaces to see if this is Atom or RDF.

It sounds like just iterating each property is going to be the best way.

Drazisil
  • 3,070
  • 4
  • 33
  • 53

3 Answers3

10

If you're trying to get the value of the property whose key is an empty string, then you can do

var value = myObject[''];

If you try to get the "first property" of an object, you can't because properties in javascript objects aren't ordered.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • This is a JSON object of the namespaces XML namespaces. Are you saying I should decode this object back to an array? Would that even work with a blank key? – Drazisil Dec 12 '12 at 21:20
  • This is correct, however you could iterate over the object's properties to get at the value. – Mike Brant Dec 12 '12 at 21:20
  • Did not know you could reference an empty string key that way. Thanks. – Drazisil Dec 12 '12 at 21:41
1

Properties aren't guaranteed to be ordered. You can however iterate over all properties to find the right one (if you know what you are looking for):

for(var prop in obj) {
    if(obj.hasOwnProperty(prop))
        doSomethingWith(obj[prop]);
}

Reference: Iterating over every property of an object in javascript using Prototype?

Then get the key by

var value = obj[key];
Community
  • 1
  • 1
Peter Rasmussen
  • 16,474
  • 7
  • 46
  • 63
  • https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty This doesn't look like it would would on what appears to be a blank property. – Drazisil Dec 12 '12 at 21:38
1

You can try this code:

var test_bject = {'test': 1, 'test2': 2, 'test3': 3}, first_value;

for (i in test) {
  first_value = test_object[i];
  break;
}
Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41