简体   繁体   中英

how to transform array into different array by extracting key values using lodash

How can I transform a big array into my won small array bu extracting keys and values using lodash. The given array consists of nested arrays as well.

Given array ->

goals= [       
 { name: 'ACTIONS', levers: [ { partName: 'Improve', statuses: [ { element 1 },{ element 2 }]}] },
 { name: 'DEFINITIONS', levers: [ { partName: 'Hardwork', statuses: [ { element 1 },{ element 2 }]}] }    
]

Transform in to an array below:

resultantArray = 
    [
       { name: "ACTIONS",partName: "Improve", statuses: [ { element1 }, { element2 } ] },
       { name: "DEFINITIONS",partName: "hardwork", statuses: [ { element1 }, { element2 } ] }
    ]

Given the example, I'm assuming that array under levers always contains only one element.

There is no real need to use lodash to solve this, all you need is a.map method and an access to object keys.

It can be done in pure JS, as well as lodash. Below are examples how to do it in both:

Pure JS:

 goals= [ { name: 'ACTIONS', levers: [ { partName: 'Improve', statuses: [ { element: 1 },{ element: 2 }]}] }, { name: 'DEFINITIONS', levers: [ { partName: 'Hardwork', statuses: [ { element: 1 },{ element: 2 }]}] } ] resJS = goals.map(el => { return { name: el.name, partName: el.levers[0].partName, statuses: el.levers[0].statuses } }) console.log(JSON.stringify(resJS, undefined, 2))

Lodash:

const _ = require('lodash')

resLodash = _.map(goals, el => {
    return {
        name: _.get(el, 'name'),
        partName: _.get(el, 'levers[0].partName'),
        statuses: _.get(el, 'levers[0].statuses')
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM