简体   繁体   中英

can't read the property title of an object in an array

Basically I was trying to console log the title of the to-do from the json- placeholder , but I get the error shown at the end:

Here is my.js file:

//starts at 14:43, sat 21/9/2019

//jsonph

const url = 'https://jsonplaceholder.typicode.com/todos?_limit=3';

async function getDataFromCinemasAPI() {
    const response = await fetch(url);
    const data = await response.json();
    //FIXME: da undefined
    for (let i = 0; i < data.length; i++) {
        console.log(data[title]);              
    }
}

getDataFromCinemasAPI();

$('.card-text.c1').html()`

Here is the error:

Uncaught (in promise) ReferenceError: title is not defined at getDataFromCinemasAPI

If you are trying to get a property whose name you know before run-time you should object.property (You can also use object["property"] , though it's not recommended). If you are trying to get a property whose name you only know at run-time then you should use object[propertyName] (where propertyName is a variable).

In the code you have supplied you are using data[title] , so you should replace it with data.title (or data["title"] ).

But the json you have supplied contains an array of objects instead of one object, so you should first get the item at that index data[i] and then get the title property data[i].title .

 const url = 'https://jsonplaceholder.typicode.com/todos?_limit=3'; async function getDataFromCinemasAPI() { const response = await fetch(url); const data = await response.json(); for (let i = 0; i < data.length; i++) { console.log(data[i].title); } } getDataFromCinemasAPI();

data is an array, so you have to access the position of the element before print a property

console.log(data[i].title)

done! with console.log(data[i]["title"]); thanks Nick Parsons!

As others have said, use square bracket notation or dot notation. However the other problem you had is that data is an array, which you're looping over so you needed data[i]["title"] or data[i].title

 const url = 'https://jsonplaceholder.typicode.com/todos?_limit=3'; async function getDataFromCinemasAPI() { const response = await fetch(url); const data = await response.json(); //FIXME: da undefined for (let i = 0; i < data.length; i++) { console.log(data[i]["title"]); } } getDataFromCinemasAPI();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM