I have an ajax function that returns data and I want to push the objects
name into an array but when I check the console, it keeps saying undefined. How can I print the certain attribute only?
$.ajax({
url: 'http://localhost:3000/list',
type: 'get',
success: function(response){
console.log(response);
console.log(response.name);
},
error: function(){
console.log('err');
}
});
When I check the results on console
//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
Your response is an object so you must identify the index of what you want to display
console.log(response[1].name); //will display "b"
Your result is in the form of array of objects
so console.log(response.name);
will not work for you. You've to add the index e.g response[1]
and then property
name like response[1].name
to get the name of 2nd element, See MDN to see more about Property Accessors
response[0].name // logs a
response[1].name // logs b
response[2].name // logs c
e.g
const response = [{_id: "1", name: "a"},{_id: "2", name: "b"},{_id: "3", name: "c"}]
console.log(response[2].name);
</div>
Since there are 3 objects each with a name, did you want to output all of them?
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}"`));
</div>