我有一个返回数据的ajax函数,我想将objects
名称推送到数组中,但是当我检查控制台时,它一直在说未定义。我该如何只打印某些属性?
$.ajax({
url: 'http://localhost:3000/list',
type: 'get',
success: function(response){
console.log(response);
console.log(response.name);
},
error: function(){
console.log('err');
}
});
当我在控制台上检查结果
//console.log(response);
(3) [{...}, {...}, {...}]
1: {_id: "1", name: "a"}
2: {_id: "2", name: "b"}
3: {_id: "3", name: "c"}
//console.log(response.name);
(3)undefined
答案 0 :(得分:2)
您的回复是一个对象,因此您必须标识要显示的内容的索引
console.log(response[1].name); //will display "b"
答案 1 :(得分:1)
您的结果采用array of objects
的形式,因此console.log(response.name);
对您不起作用。您必须先添加索引,例如response[1]
,然后再添加property
之类的名称response[1].name
,以获得第二个元素的名称,请参见MDN以了解有关属性访问器的更多信息
response[0].name // logs a
response[1].name // logs b
response[2].name // logs c
例如
const response = [{_id: "1", name: "a"},{_id: "2", name: "b"},{_id: "3", name: "c"}]
console.log(response[2].name);
答案 2 :(得分:1)
由于每个对象都有3个名称,您是否要全部输出?
const response = [{_id: "1", name: "a"},{_id: "2", name: "b"},{_id: "3", name: "c"}];
console.log(response.map(({name})=>name).join());
// or one at a time
response.forEach(({name}, index)=>console.log(`${index}: "${name}"`));