1

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 } ] }
    ]

1 Answer 1

2

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')
    }
})
Sign up to request clarification or add additional context in comments.

2 Comments

The assumption is correct but unable to view you code result.
Just updated the answer and made Pure JS snippet runnable. I don't know how to create a runnable snippet using lodash though, but the output is the same.

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.