0

So I have an object that looks like this:

Object
    maddiekeller: Object
    rickbross: Object
        firstname:"Rick"
        lastname:"Bross"
        firstname:"1234 Fictional Drive"
        ...
    __proto__: Object

and I can pull any of the first names out by saying:

alert(potentialmodels.rickbross.firstname);
//Alerts "Rick"

Now how can I store all of the first names from all the models in an array? Am I able to loop through them when they all have different firstnames?

potentialmodels.*differentfirstname*.firstname

Here is how I am generating the object:

$result = mysql_query("SELECT * FROM `potentials`") or die(mysql_error());
$rows = array();

//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
    $rows[strtolower($r['firstname'].$r['lastname'])] = $r;
}

$myJSON =  json_encode($rows);

and my JavaScript:

var potentialModels = <?php print($myJSON); ?>;
console.log(potentialModels);
console.log(potentialModels.rickbross.firstname);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Rick Bross
  • 1,060
  • 3
  • 16
  • 39
  • 2
    FYI, [there is not such thing as a JSON object](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). What you have is simply an object. Even though you encode the data as JSON on the server side, when the JavaScript is evaluated, you just have an object. Your problem is not related to JSON at all. – Felix Kling Apr 15 '13 at 09:52
  • to be js array or php array, which one ? – egig Apr 15 '13 at 09:59
  • Thanks Felix! Im a newbie. – Rick Bross Apr 15 '13 at 10:14

2 Answers2

0

Reorganise your Object to a numeric array:

$result = mysql_query("SELECT * FROM `potentials`") or die(mysql_error());
$rows = array();

//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
    $rows[] = $r; // numeric array
}

$myJSON =  json_encode($rows);

Get the firstnames as an array:

var result = JSON.parse(yourJSONstring);
var firstnames = [];
for (var i = 0; i < result.length; i++) {
    firstnames.push(result[i].firstname);
}
Zim84
  • 3,404
  • 2
  • 35
  • 40
  • If you still assign the value like the OP does, then `potentialModels` will already be an array (not a string containing JSON). – Felix Kling Apr 15 '13 at 09:57
0

You can use Object.keys to get an array of your models, and you can get an array of your model's name out of it using Array.prototype.map.

Example:

var potentialmodels = {
    "maddiekeller": {
        "firstname":"Maddie",
        "lastname":"Keller"
        },
    "rickbross": {
        "firstname":"Rick",
        "lastname":"Bross"
    }
}

var nameArray = Object.keys(potentialmodels).map(function(model) {
                            return potentialmodels[model].firstname
                        });

// nameArray = ["Maddie", "Rick"]

jsFiddle example: http://jsfiddle.net/cgqxe/

Cattode
  • 856
  • 5
  • 11