1

I need to extract, from this array

const mylist = [
            {
               "key": "",
               "doc_count": 3
            },
            {
               "key": "IT",
               "doc_count": 1
            }
         ]

an array of the values of key:

["", "IT"]

Today I use a simplistic approach

finalList = []
_.forEach(myList, function (element) {
  finalList.push(element.key)
})

but I saw that lodash has several methods which are almost the ones for my case: _.zip/_.unzip, _.fromPairs/_.toPairs and _.zipObject

Is there a way to simplify this code based on a lodash method?

1 Answer 1

1

You can do this easily without lodash by using Array#map to extract the keys to an array:

const mylist = [{"key":"","doc_count":3},{"key":"IT","doc_count":1}];

const result = mylist.map(({ key }) => key);

console.log(result);

If you already have lodash in your project you can use _.map():

const mylist = [{"key":"","doc_count":3},{"key":"IT","doc_count":1}];

const result = _.map(mylist, 'key');

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

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

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.