如何隔离first_name
键以在以下对象中输出其值?
{
"first_name": "D",
"last_name": "N",
"phone_number": 1233414234
}
答案 0 :(得分:2)
使用点表示法或使用括号表示法。详细了解property accessors。
var object = { first_name: "D", last_name: "N", phone_number: 1233414234 };
// dot notation
console.log(object.first_name);
// bracket notation
console.log(object['first_name']);
对于一组对象,您可以使用Array#map
-
var array = [{"first_name":"D","last_name":"N","phone_number": 1233414234},{"first_name":"P","last_name":"T","phone_number": 1233414234}],
first_names = array.map(function (a) {
return a.first_name;
});
console.log(first_names);
答案 1 :(得分:1)
您可以使用.
或[]
var x = {"first_name":"D","last_name":"N","phone_number": 1233414234};
alert(x.first_name);
alert(x['first_name']);
参考是here。
修改强>
基于另一个答案中的评论中的OP问题:如果要迭代数组的对象,可以使用每个。
var array = [{"first_name":"D","last_name":"N","phone_number": 1233414234},{"first_name":"P","last_name":"T","phone_number": 1233414234}];
$.each(array, function(idx) {
alert(array[idx].first_name);
});
OR
var array = [{"first_name":"D","last_name":"N","phone_number": 1233414234},{"first_name":"P","last_name":"T","phone_number": 1233414234}];
$.each(array, function(idx, obj) {
alert(obj.first_name);
});