1

Im trying to loop through an array of objects, which have different keys. Is there a way that I can pick an object based on they key?

var array = [
  {
    "1400": "Accident and Health"
  },
  {
    "100": "Life"
  },
  {
    "1300": "Pension"
  }
]
var a = "100";
var pop = _.pick(array,a);
console.log(pop);

Desired output:

Life

Thank you!

3 Answers 3

3

You could use the in operator.

var array = [{ 1400: "Accident and Health" }, { 100: "Life" }, { 1300: "Pension" }];

var result = (key => array.find(item => key in item)[key])(100);

console.log(result);

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

Comments

0

var array = [
  {
    "1400": "Accident and Health"
  },
  {
    "100": "Life"
  },
  {
    "1300": "Pension"
  }
]
var a = "100";


var pop = _.map(array, function(currentObject) {
  var b= _.pick(currentObject, a);
  if(!_.isEmpty(b))
    console.log(b);
});
<script src="http://underscorejs.org/underscore-min.js"></script>

Comments

0

Lodash 4.17.2

_.chain(array).map('100').compact().head().value();

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.