javascript - Turn object into array, add object as new element -
trying transform object of objects:
var items: { item_a: { state: 'item_a status' }, item_b: { state: 'item_b status' } }; into array of objects, whilst adding new array element object (the object key):
var items = [{ name: 'item_a', state: 'item_a status' }, { name: 'item_b', state: 'item_b status' }]; my naive attempt, works, thus:
var arrayofitems = []; for(var x in items){ var itemobj = { name: x }; for(var y in items[x]){ itemobj[y] = items[x][y]; } arrayofitems.push(itemobj); } i'm wondering if there's cleaner way this, using maybe underscore/lodash?
var newitems = _.map(items, function(item, key){ item.name = key; return item; }); console.log(newitems);
Comments
Post a Comment