Javascript:过滤掉一个对象数组并根据键而不是值进行选择

时间:2021-03-10 12:20:06

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 个解决方案

#1


2  

You could use the in operator.

您可以使用in运算符。

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

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

console.log(result);

#2


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>

#3


0  

Lodash 4.17.2

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

#1


2  

You could use the in operator.

您可以使用in运算符。

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

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

console.log(result);

#2


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>

#3


0  

Lodash 4.17.2

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