javascript - Mapping out JSON structure -
i'm parsing json message looks like:
{ staff : [ {name : 'john', department : 'math'}, {name : 'sally', department : 'science'}, ], students : [ {name : 'bob', department : 'law'}, {name : 'lisa', department : 'it'} ] }
from i'd pull out array of each separate value. i.e.
names -> ['john', 'sally', 'bob', 'lisa']
at moment i'm doing like
var names = []; msg.staff.foreach(function(e) { names.push(e.name) }) msg.students.foreach(function(e) { names.push(e.name)})
this feels overly verbose, wondering if there's cleaner way approach (for every attribute). i'm including lodash in project.
you can use _.pluck
value of property of each object in array:
_.pluck(obj.staff.concat(obj.students), 'name')
Comments
Post a Comment