Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the value of an object's property where the key is a blank string

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.

like image 786
Drazisil Avatar asked Dec 12 '12 21:12

Drazisil


People also ask

How do you check if an object has a blank key-value?

keys method to check for an empty object. const empty = {}; Object. keys(empty). length === 0 && empty.

Can empty string be object key?

Yes, technically its totally valid and you can safely use it. An object key needs to be a "string", which does not exclude an empty string.

Can the key of an object be a string?

Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.


2 Answers

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.

like image 182
Denys Séguret Avatar answered Sep 21 '22 05:09

Denys Séguret


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];
like image 38
Peter Rasmussen Avatar answered Sep 18 '22 05:09

Peter Rasmussen