0

我用 listjs (listjs.com) 列了一个列表

现在我正在使用函数 get(),这会给我这个回报:

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

现在我只想用纯 javascript 获取名称 id。

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

抱歉不具体......我想从返回值:

{ uid:2,名称:“马克” ... }

itemValues.name -> Marc

乌馆

忘记使用 uid 函数(“id”)。当我使用 values() 时,它会起作用。谢谢你的回答。

更新的小提琴 小提琴

4

2 回答 2

2

您可以使用数组过滤方法(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);
    }
}
于 2013-12-21T22:21:35.413 回答
2

您的 id 字段称为 uid,要获取对象的值,您需要在结果上调用 .values,因此:

function getUserName(uid) {
    var itemValues = hackerList.get("uid", uid)[0].values();
    console.log("The name of the user is: " + itemValues.name);
}
于 2013-12-21T22:23:33.013 回答