简体   繁体   中英

Cant retrieve the data from the Array by using method(passing) index as argument

Can't get the Array item by using method() while passing index as argument it shows as undefined

export class DataService {
    public list = [
        { id: 11, name: 'Mr. Nice' },
        { id: 12, name: 'Narco' },
        { id: 13, name: 'Bombasto' },
        { id: 14, name: 'Celeritas' },
        { id: 15, name: 'Magneta' },
        { id: 16, name: 'RubberMan' },
        { id: 17, name: 'Dynama' },
        { id: 18, name: 'Dr IQ' },
        { id: 19, name: 'Magma' },
        { id: 20, name: 'Tornado' }
    ]
    getList() {
        return this.list;
    }


    update(num, updated) {
        let list = this.getList()
        console.log(typeof (num))
        console.log(this.list[num])
    }

Your array contains objects, but you want to search by id which is a property of those objects. You have to use filter :

console.log(this.list.find(el => el.id === id))

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