我如何从没有键的 JSON 对象中获取值
How can i get a value from a JSON object with no key
我正在发出一个 http 请求,然后我从 SQL table 中获取值。
router.get('/', function(req, res, next) {
controller.getAllPosts( function(err,posts){
if(err){
res.status(500);
res.end();
}else{
res.json(posts);
}
我得到的回复是这样的:
[
{
"id_post": 1,
"description": "Hola",
"username": "jumavipe",
"image": "1.jpg"
},
{
"id_post": 2,
"description": "no se",
"username": "jacksonjao",
"image": "2.jpg"
},
{
"id_post": 3,
"description": "nuevo tatuaje de bla bla bla",
"username": "jumavipe",
"image": "3.jpg"
}
]
如何只从 post 3
中获取描述
我做不到:
var desc= posts[2].description
我在网上看了看,然后尝试了这样的操作:
var description = posts.getJSONObject("LabelData").getString("description");
如果我的 json 数组没有键,我应该在 getJSONObject()
中使用什么作为参数。
我找不到有用的东西。如何从 json 数组的一个对象中获取该值?
使用Array.prototype.find
如果您没有任何浏览器兼容性问题,您可以使用Array.prototype.find
var posts = [
{
"id_post": 1,
"description": "Hola",
"username": "jumavipe",
"image": "1.jpg"
},
{
"id_post": 2,
"description": "no se",
"username": "jacksonjao",
"image": "2.jpg"
},
{
"id_post": 3,
"description": "nuevo tatuaje de bla bla bla",
"username": "jumavipe",
"image": "3.jpg"
}
];
var post = posts.find(function(item) {
return item.id_post == 3;
});
console.log(post.description);
使用Array.prototype.filter
Array.prototype.filter
几乎大多数浏览器都支持,并且可以正常工作。
var selected_posts = posts.filter(function(item) {
return item.id_post == 3;
});
console.log(selected_posts[0].description);
我正在发出一个 http 请求,然后我从 SQL table 中获取值。
router.get('/', function(req, res, next) {
controller.getAllPosts( function(err,posts){
if(err){
res.status(500);
res.end();
}else{
res.json(posts);
}
我得到的回复是这样的:
[
{
"id_post": 1,
"description": "Hola",
"username": "jumavipe",
"image": "1.jpg"
},
{
"id_post": 2,
"description": "no se",
"username": "jacksonjao",
"image": "2.jpg"
},
{
"id_post": 3,
"description": "nuevo tatuaje de bla bla bla",
"username": "jumavipe",
"image": "3.jpg"
}
]
如何只从 post 3
中获取描述我做不到:
var desc= posts[2].description
我在网上看了看,然后尝试了这样的操作:
var description = posts.getJSONObject("LabelData").getString("description");
如果我的 json 数组没有键,我应该在 getJSONObject()
中使用什么作为参数。
我找不到有用的东西。如何从 json 数组的一个对象中获取该值?
使用Array.prototype.find
如果您没有任何浏览器兼容性问题,您可以使用Array.prototype.find
var posts = [
{
"id_post": 1,
"description": "Hola",
"username": "jumavipe",
"image": "1.jpg"
},
{
"id_post": 2,
"description": "no se",
"username": "jacksonjao",
"image": "2.jpg"
},
{
"id_post": 3,
"description": "nuevo tatuaje de bla bla bla",
"username": "jumavipe",
"image": "3.jpg"
}
];
var post = posts.find(function(item) {
return item.id_post == 3;
});
console.log(post.description);
使用Array.prototype.filter
Array.prototype.filter
几乎大多数浏览器都支持,并且可以正常工作。
var selected_posts = posts.filter(function(item) {
return item.id_post == 3;
});
console.log(selected_posts[0].description);