Найти объект в массиве с соответствующим ключом, используя lodash - PullRequest
0 голосов
/ 07 февраля 2020

У меня есть массив объектов, каждый объект имеет уникальный ключ. Пример:

const myArray = [
{uKey1: 'hey', otherValue: 1},
{uKey2: 'hey', otherValue: 1},
{uKey3: 'hey', otherValue: 1}
];

Я хочу использовать loda sh, чтобы сделать что-то вроде

lodash(myArray, 'uKey2')

И заставить его вернуть объект с помощью uKey2

Ответы [ 2 ]

0 голосов
/ 07 февраля 2020

Вы можете передать имя ключа _.find во втором аргументе:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<script>
  const myArray = [{
      uKey1: 'hey',
      otherValue: 1
    },
    {
      uKey2: 'hey',
      otherValue: 1
    },
    {
      uKey3: 'hey',
      otherValue: 1
    }
  ];

  console.log(_.find(myArray, 'uKey1'))
  console.log(_.find(myArray, 'uKey2'))
  console.log(_.find(myArray, 'uKey3'))
</script>
0 голосов
/ 07 февраля 2020

Просто объедините _.find с _.has.

Вы даже можете создать миксин (он же плагин), как показано ниже.

Чистая версия JS не так уж и плоха.

_.mixin({
  findObjectByPresentKey : function(arr, key) {
    return _.find(arr, function(obj) {
      return _.has(obj, key);
    })
  }
});

const myArray = [
  { uKey1: 'hey', otherValue: 1 },
  { uKey2: 'hey', otherValue: 1 },
  { uKey3: 'hey', otherValue: 1 }
]

// In-line
console.log(_.find(myArray, 'uKey3'))

// As a plugin
console.log(_.findObjectByPresentKey(myArray, 'uKey3'))

// Pure JS (Edge)
console.log(myArray.find(obj => obj.hasOwnProperty('uKey3')));

// IE 9+
console.log(myArray.filter(obj => obj.hasOwnProperty('uKey3')).pop());
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Пожалуйста, обратитесь к: _.find(collection, [predicate=_.identity], [fromIndex=0])

// The `_.property` iteratee shorthand.
_.find(users, 'active');
// => object for 'barney'
...