所以我有一个看起来像这样的对象:
Object
maddiekeller: Object
rickbross: Object
firstname:"Rick"
lastname:"Bross"
firstname:"1234 Fictional Drive"
...
__proto__: Object
我可以通过以下方式提取任何名字:
alert(potentialmodels.rickbross.firstname);
//Alerts "Rick"
现在我如何存储阵列中所有模型的所有名字?当他们都有不同的名字时,我能够遍历它们吗?
potentialmodels.*differentfirstname*.firstname
以下是我生成对象的方法:
$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);
和我的JavaScript:
var potentialModels = <?php print($myJSON); ?>;
console.log(potentialModels);
console.log(potentialModels.rickbross.firstname);
答案 0 :(得分:0)
将您的对象整理到数字数组:
$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);
将名字作为数组获取:
var result = JSON.parse(yourJSONstring);
var firstnames = [];
for (var i = 0; i < result.length; i++) {
firstnames.push(result[i].firstname);
}
答案 1 :(得分:0)
您可以使用Object.keys获取模型数组,然后使用Array.prototype.map从中获取模型名称数组。
示例:
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示例:http://jsfiddle.net/cgqxe/