Вопрос

I'm trying to use a string as a key in an object literal and then use that string in a function that adds that string to a data-attribute in an HTML li element. The basic idea is to create a user id and then get to a specific user for update/delete. The create part is working fine.

First I need to get the info into my li elements so that clicking gives me the id that I want. The code below works, but only because I included the id inside the object. It seems stupid and wrong to duplicate the string--the userguid key--inside the object just to use it.

users = {
  "0c7270bd-38e8-4db2-ae92-244de019c543": {
    datecreated: "2013-10-15",
    email: "jimmy@example.com",
    firstname: "Jimmy",
    lastname: "Smith",
    username: "jimmysmith",
    password: "foobar",
    notify: "barbour@4j.lane.edu",
    userguid: "0c7270bd-38e8-4db2-ae92-244de019c543"
  },
  "0c7270bd-38e8-4db2-ae92-244de019mju7": {
    datecreated: "2013-10-16",
    email: "mary@example.com",
    firstname: "Mary",
    lastname: "Jones",
    username: "maryjones",
    password: "foobar2",
    notify: "barbour@4j.lane.edu",
    userguid: "0c7270bd-38e8-4db2-ae92-244de019mju7"
  }
};

The function using it:

displayUserList = function() {
  var newHTML;
  users = JSON.parse(localStorage["users"]);
  newHTML = [];
  $.each(users, function(index, user) {
    return newHTML.push('<li data-userguid="' + user.userguid + '" data-firstname="' + user.firstname + '"><span class="userfullname">' + user.firstname + ' ' + user.lastname + '</span></li>');
  });
  /*
    jquery css going on here
  */
};

I want to get userguid out of the inside of the object. I've tried using a variety of things to target that string and bring it into the html but nothing works. I also want to be able to target it for update and delete.

I've tried

user      user[user]   user.user

I'm starting to feel like I'm missing a basic rule of using object literals, but I haven't found it in my searches.

Thanks for any help.

Charlie Magee

Это было полезно?

Решение

When iterating over an object with $.each, the index parameter receives the keys, so you can do:

newHTML.push('<li data-userguid="' + index + '" data-firstname="' + user.firstname + '"><span class="userfullname">' + user.firstname + ' ' + user.lastname + '</span></li>');

You don't need return on this statement. The only thing $.each() does with the return value is test it for ===false -- if it is, the loop ends.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top