【问题标题】:Function to find object in array using one or more conditions使用一个或多个条件在数组中查找对象的函数
【发布时间】:2019-08-22 17:41:26
【问题描述】:

我正在寻找一种普通的 javascript 解决方案来使用一个或多个条件来查找对象。

理想情况下,我想使用与 lodash.find 类似的语法和一个可以接受一个或多个条件的可重用函数:

_.find(products, {code:"BLK")
_.find(products, {code:"BLK", sale: false})

就我而言,我正在寻找一个对象,所以我更喜欢find 而不是filter

const products = [
  {
    title: "Shirt",
    color: "Black",
    code: "BLK",
    sale: true
  },
  {
    title: "Better Shirt",
    color: "Black",
    code: "BLK",
    sale: false
  },
  {
    title: "Blue Shirt",
    color: "Blue",
    code: "BLU",
    sale: false
  }
]

// Lodash find using multiple conditions
console.log(_.find(products, {code:"BLK", sale: false}))

// Find all using one condition
console.log(products.filter(product => product.color === 'Black'))

// Find single with multiple conditions
console.log(products.find(product => product.color === 'Black' && product.sale === false ))
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

如何在简单的原生 js 中从 lodash 模拟 _.find 的功能?

【问题讨论】:

标签: javascript


【解决方案1】:

您可以使用Array.prototype.find 克隆 lodash 行为,并在回调中检查您提供的数组中各个对象的每个键和值,以及使用Array.prototype.every() 作为第二个参数obj 传递的过滤器对象:

const products = [
  {
    title: "Shirt",
    color: "Black",
    code: "BLK",
    sale: true
  },
  {
    title: "Better Shirt",
    color: "Black",
    code: "BLK",
    sale: false
  },
  {
    title: "Blue Shirt",
    color: "Blue",
    code: "BLU",
    sale: false
  }
]
function find(arr, obj){
  return arr.find((ele) => {
    return obj && Object.keys(obj).every(key => ele[key] === obj[key]);
  }) || arr[0];
}

// Lodash find using multiple conditions
console.log(find(products, {code:"BLK", sale: false}));
console.log(find(products, {title:"Blue Shirt", sale: false}));
console.log(find(products, undefined));
console.log(find(products, {}));
console.log(find(products, {title:"Better Shirt", sale: true}))

【讨论】:

  • 完美??。谢谢
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2018-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-01
  • 2016-06-15
相关资源
最近更新 更多