简体   繁体   中英

get values from {id:3,name:“John”} from list.js

I made a list with listjs (listjs.com)

Now i'm using the function get(), this wil give me this return:

itemsInList = [
    { id: 1, name: "Jonny" }
    , { id: 2, name "Gustaf" }
];
listObj.get("id", 2); -> return { id: 2, name: "Gustaf" }

Now i'm want to get the name id with pure javascript only.

function getUserName(uid) {
    var itemValues = hackerList.get("id", uid)[0];
    console.log("The name of the user is: " + itemValues.name);
    // or use alert..
    //alert("The name of the user is: " + itemValues.name);
}

Sorry not concrete... I want from the return value:

{ uid: 2, name: "Marc" ... }

to itemValues.name -> Marc

Udate

Forgot to use uid function ("id"). When I use values() it will work. Thank you for the answer.

Updated Fiddle Fiddle

You can use the arrays filter method (IE9+):

// Pure javascript list
var hackerList = [
    { uid: 1, name: 'John' },
    { uid: 2, name: 'Marc' }
];

function getUserName(uid) {
    var hackers = hackerList.filter(function(hacker) {
        return hacker.uid === uid;
    });

    if(hackers.length > 0) {
        console.log("The name of the user is: " + hackers[0].name);
    }
}

Your id field is called uid, and to get to the values of the object, you need to call .values on the result, so:

function getUserName(uid) {
    var itemValues = hackerList.get("uid", uid)[0].values();
    console.log("The name of the user is: " + itemValues.name);
}

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