【问题标题】:get values from {id:3,name:"John"} from list.js从 list.js 获取 {id:3,name:"John"} 的值
【发布时间】:2013-12-21 22:05:24
【问题描述】:

我用 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, name: "Marc" ... }

itemValues.name -> Marc

Udate

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

更新小提琴 Fiddle

【问题讨论】:

  • 您需要帮助解决什么问题?

标签: javascript html object listjs


【解决方案1】:

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

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

【讨论】:

  • 我试过了,但这不是jquery的函数吗?我得到:未捕获的类型错误:无法调用未定义的方法“值”
  • 您是否将hackerList.get("id", uid) 更改为hackerList.get("uid", uid) ?在您的小提琴示例中,您将 id 字段命名为“uid”
【解决方案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);
    }
}

【讨论】:

  • 这是一种方式。但它会再次搜索列表,我想使用 listjs,对所有浏览器也更好。谢谢。
  • 我误解了你的问题,以为你出于某种原因不想 list.js...
猜你喜欢
  • 1970-01-01
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多