0

I have an Object array:

let products = [{ code: 'a', num: 1 }, { code: 'b', num: 2 }];

I want to get the codes array: ['a', 'b'].

This is how I am doing now using lodash:

let codes = [];
_.forEach(products, (product) => {
  codes.push(product.code);
});

Is there any smart way to do this?

3 Answers 3

3

Yeah, there is a pure JavaScript solution:

let codes = products.map(obj => obj.code);
Sign up to request clarification or add additional context in comments.

Comments

2

You can use map() for lodash:

let codes = _.map(products, 'code');

let products = [{ code: 'a', num: 1 }, { code: 'b', num: 2 }];

let codes = _.map(products, 'code');

document.write('<pre>' + JSON.stringify(codes, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.12.0/lodash.js"></script>

Comments

1

Use vanilla JavaScript Array.map

var arr = [{ code: 'a', num: 1 }, { code: 'b', num: 2 }];

var newArr = arr.map(function(obj){
  return obj.code;

})

console.log(newArr)

   var arr = [{
     code: 'a',
     num: 1
   }, {
     code: 'b',
     num: 2
   }];

   var newArr = arr.map(function(obj) {
     return obj.code;

   })

    console.log(newArr)

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.