I'm trying to take an array of objects and pick out the data that I only need. For example, below I only want the name, id, and users properties from the originalArray.
I figured out how to do it at the first level of iteration, but how do I do the same for the users array of objects? I only want to include the values in the allowedUserProps array found below.
https://jsfiddle.net/n8zw47cd/
Original Array
var originalArr = [
{
name: 'Obj 1',
id: 0,
something: 'else',
users: [{first_name: 'Joe', last_name: 'Smith'}]
},
{
name: 'Obj 2',
id: 1,
something: 'else',
users: [{first_name: 'Jane', last_name: 'Doe'}]
},
];
Desired Output
[
{
name: 'Obj 1',
id: 0,
users: [{first_name: 'Joe'}]
},
{
name: 'Obj 2',
id: 1,
users: [{first_name: 'Jane'}]
},
];
I'm using Underscore's pick method to return whitelisted values, but how can I change the users array of objects too?
function changeArray(arr) {
var allowedProps = ['name', 'id', 'users'];
var allowedUserProps = ['first_name'];
return _.map(arr, function(item) {
return _.pick(item, allowedProps);
});
}
var transformed = changeArray(originalArr);