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

1.2k views Asked by At

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

2

There are 2 answers

2
Stephen On BEST ANSWER

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);
}
2
Hallvar Helleseth On

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);
    }
}