简体   繁体   中英

Flatten javascript array of objects with underscore.js

I have a javascript array of object that looks like this:

"partners":[{"username":"fangonk","profileImg":"fangonk.jpg"},
            {"username":"jane","profileImg":"jane.jpg"},
            {"username":"tom_jones","profileImg":"tom.jpg"}]

I would like to output the value of each array's key using the underscore library. So for each object, I'd like to output something that looks like this:

<h1>Username Value</h1><img src="profileImg Value here" />

A bit confused about your "source", but I think you're just trying to do this:

_.each(partners, function(p) { document.write('<h1>' + p.username + '</h1>\
  <img src="' + p.profileImg + '" alt="' + p.username + '" />'); }
//substitute some DOM method (e.g. jquery().append) for document.write

Is this the result you're looking for?

this would only be applicable if your source looked more like:

var partners = [{"username":"fangonk","profileImg":"fangonk.jpg"},
                {"username":"jane","profileImg":"jane.jpg"},
                {"username":"tom_jones","profileImg":"tom.jpg"}];

EDIT:

var someBiggerObject = { 
  partners: [
    {"username":"fangonk","profileImg":"fangonk.jpg"},
    {"username":"jane","profileImg":"jane.jpg"},
    {"username":"tom_jones","profileImg":"tom.jpg"}
  ]
};

_.each(someBiggerObject.partners, function(p) { document.write('<h1>' + p.username + '</h1>\
  <img src="' + p.profileImg + '" alt="' + p.username + '" />'); }
//substitute some DOM method (e.g. jquery().append) for document.write

The right way to do this is _.template

Example

If your structure is like this:

var list = {"partners":[ 
    {"username":"fangonk","profileImg":"fangonk.jpg"},
    {"username":"jane","profileImg":"jane.jpg"},
    {"username":"tom_jones","profileImg":"tom.jpg"}
]};

You can create the repeated item template (note type="text/html" )

<script type="text/html" id="userItemTemplate">
    <h1><%= username %></h1><img src='<%= profileImg %>' />
</script>

and put each item into the template via a loop

var uIT = $("#userItemTemplate").html();
_.each(list.partners,function(user){
    $("#target").append(_.template(uIT,user));        
});

OR

put the loop into your template

<script type="text/html" id="userTemplate">
    <% _.each(partners,function(user,key,list){ %>
    <h1><%= user.username %></h1><img src='<%= user.profileImg %>' />
    <% }); %>
</script>

then push the whole array in

var uT = $("#userTemplate").html();
$("#target2").html(_.template(uT,list));

Note that I am using lodash instead of underscore. It's compatible for the most part, but I prefer lodash because the benchmarks are faster and the library is maintained well.

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