convert array of object to array of string - 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()
No Lodash, but maybe:
var arr = [];
x.forEach(function(item, index) {
arr.push(item[index].name)
});
console.log(arr)
This assuming the object key keeps increasing, 0, 1, 2....n