Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new array from child object properties

I have an array:

[
    {
        meta:'abc'
        data:
        {
            name:'asd',
            title: 'bbb'
        }
    },
    {
        meta:'abc'
        data:
        {
            name:'asd',
            title: 'bbb'
        },
    {
        meta:'abc'
        data:
        {
            name:'asd',
            title: 'bbb'
        }
    }
]

I want to convert it to new array, which will be:

[
    {
        name:'asd',
        title: 'bbb'
    },
    {
        name:'asd',
        title: 'bbb'
    {
        name:'asd',
        title: 'bbb'
    }
]

I want to take only the data elements, and to create from them a new array. How can I do it the fastest way? And how can I do it with lodash?

Thanks!

like image 901
user3712353 Avatar asked Sep 13 '25 18:09

user3712353


2 Answers

You can use _.map

var array = [{
  meta: 'abc',
  data: {
    name: 'asd',
    title: 'bbb'
  }
}, {
  meta: 'abc',
  data: {
    name: 'asd',
    title: 'bbb'
  }
}, {
  meta: 'abc',
  data: {
    name: 'asd',
    title: 'bbb'
  }
}];

console.log(_.map(array, 'data'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.2.0/lodash.js"></script>
like image 98
Oleksandr T. Avatar answered Sep 16 '25 07:09

Oleksandr T.


Just you need is the map() native javascript method to arrays:

//considere that 'someArray' is the same as your.

var newArray = someArray.map(function(item){
    return {name: item.data.name, title: item.data.title};
});
like image 45
Christian G Fritsch Avatar answered Sep 16 '25 08:09

Christian G Fritsch