简体   繁体   中英

How can I pass parameter correctly?

const root = {
    user: (id) => {
        console.log("returning object " + JSON.stringify(id.id) + " " + JSON.stringify(storage.select("users", id.id)))
        return storage.select("users", id.id)
    }
}

I want to call the arrow function in root.user but I think I can't pass the parameter correctly, so I tried this --> let user = root.user('101') and on the console I got this -->

returning object undefined

[{"firstName":"Gokhan","lastName":"Coskun","login":"gcoskun","id":101}]
{"firstName":"George","lastName":"Clooney","login":"gclooney"}
[{"firstName":"Gokhan","lastName":"Coskun","login":"gcoskun","id":101}]

I wanted the user with the id 101 get returned and got instead all of the users returned.

Why are you doing id.id but passing a string ? You either pass an object with an id prop ( root.user({ id: '101' }) ) or replace id.id with simply id .

Also, it looks like the id fields in your user objects are of type number , while you are passing a string , so depending on the logic inside storage.select you might have to change that.

Passing a number id :

 // Just mocking it for the example: const storage = { select(key, id) { return [ { firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 }, { firstName: 'George', lastName: 'Clooney', login: 'gclooney' }, { firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 }, // Depending on the logic here, these types need to match. // Using == instead of === so that it's not required here. ].filter(user => user.id == id) }, }; const root = { user: (id) => { console.log(`ID = ${ id }`); // We make sure we only return a single user or null if there isn't one: return storage.select('users', id)[0] || null; }, }; const user = root.user('101'); console.log(user);

Passing an object with an id prop of type number :

 // Just mocking it for the example: const storage = { select(key, id) { return [ { firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 }, { firstName: 'George', lastName: 'Clooney', login: 'gclooney' }, { firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 }, // Depending on the logic here, these types need to match. // Using == instead of === so that it's not required here. ].filter(user => user.id == id); }, }; const root = { user: (query) => { console.log(`ID = ${ query.id }`); // We make sure we only return a single user or null if there isn't one: return storage.select('users', query.id)[0] || null; }, }; const user = root.user({ id: '101' }); console.log(user);

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