0

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 ?

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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()

2 Comments

working now, thanks, what if i nedd to get the new array but with key - value combination ? like [{5,'xxx'}, {6,'yyy'}] ? how to implement that ?
Have added a snippet showing different values being returned for each item.
1

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

Comments

0

How to: _.map(data, "name").toString()

JavaScript (example):

var data = [
  {
    0:{
       id:5,
       name:'xxx'
      }
  },
  {
    1:{
       id:6,
       name:'yyy'
      }
  }
];

console.log(_.map(data, "name").toString());

Output:

xxx,yyy

Human readable

_.map(data, "name").join(', ')
// xxx, yyy

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.