How to split array dynamically based on single value in JavaScript Node.js -
i need split array dynamically based on single value in javascript.
i've got array:
var datastuff = [ { name: 'apple', tag: 'fruit', price: '2,5'}, { name: 'bike', tag: 'sport', price: '150'}, { name: 'kiwi', tag: 'fruit', price: '1,5'}, { name: 'knife', tag: 'kitchen', price: '8'}, { name: 'fork', tag: 'kitchen', price: '7'} ];
and expect arrays split tag, eg.
var fruit = [ { name: 'apple', tag: 'fruit', price: '2,5'}, { name: 'kiwi', tag: 'fruit', price: '1,5'} ]; var sport = [ { name: 'bike', tag: 'sport', price: '150'} ]; var kitchen = [ { name: 'knife', tag: 'kitchen', price: '8'}, { name: 'fork', tag: 'kitchen', price: '7'} ];
if in datastuff array more tags in result more arrays. anyway don't have idea how should this. i'm using node.js + jade (for view), , think best idea @ view because have put each array in table. maybe this:
// basic table tbody - each item in datastuff tr td= item.name td= item.tag td= item.price // other tables - each item in datastuff item.tag.push(item); // adding items array based on tag // won't work // still how should draw table?
i grateful help
you use object grouped items. works tags , allows list of tags object.keys(grouped)
, if required.
var datastuff = [{ name: 'apple', tag: 'fruit', price: '2,5' }, { name: 'bike', tag: 'sport', price: '150' }, { name: 'kiwi', tag: 'fruit', price: '1,5' }, { name: 'knife', tag: 'kitchen', price: '8' }, { name: 'fork', tag: 'kitchen', price: '7' }], grouped = object.create(null); datastuff.foreach(function (a) { grouped[a.tag] = grouped[a.tag] || []; grouped[a.tag].push(a); }); document.write(object.keys(grouped)); document.write('<pre>' + json.stringify(grouped, 0, 4) + '</pre>');
Comments
Post a Comment