if i have the following array :
[
{
0:{
id:5,
name:'xxx'
}
},
{
1:{
id:6,
name:'yyy'
}
}
]
and i need to convert it to
['xxx', 'yyy']
how to implement that with Lodash ?
You can use Lodash's map method.
var data = [
{
0:{
id:5,
name:'xxx'
}
},
{
1:{
id:6,
name:'yyy'
}
}
];
var arr = _.map(data, function(element, idx) {
return element[idx].name;
});
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
As yBrodsky pointed out, this assumes the object key continues to increase by one each time.
Here's a solution that makes use of lodash's flatMapDeep to extract the values before plucking the name:
let data = [
{
0:{
id:5,
name:'xxx'
}
},
{
1:{
id:6,
name:'yyy'
}
}
]
let result = _(data)
.flatMapDeep(_.values)
.map('name')
.value()
Edit Change the map to return a different value for each item. e.g to return the id and name as a key value pair you could do this:
let result = _(data)
.flatMapDeep(_.values)
.map( item => ({[item.id]: item.name}) )
.value()