Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping out JSON structure

I'm parsing a JSON message which looks something like:

{ 
    staff : [
       {name : 'John', department : 'Math'},
       {name : 'Sally', department : 'Science'},
    ],
    students : [
       {name : 'Bob', department : 'Law'},
       {name : 'Lisa', department : 'IT'}
    ]
}

From which I'd like to pull out an array of each separate value. i.e.

names -> ['John', 'Sally', 'Bob', 'Lisa']

At the moment I'm doing something 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, just wondering if there's a cleaner way to approach this (for every attribute). I'm already including lodash in this project.

like image 945
ioseph Avatar asked May 07 '26 08:05

ioseph


2 Answers

You can use _.pluck to get the value of a property of each object in an array:

_.pluck(obj.staff.concat(obj.students), 'name')
like image 95
Jordan Running Avatar answered May 09 '26 22:05

Jordan Running


Your instinct is right; you don't need a mutable array to do this with lodash.

_(obj).map().flatten().pluck('name').value();

This version works for any number of array values in o.

JSBin

like image 44
joews Avatar answered May 09 '26 21:05

joews



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!