【问题标题】:Check if an array contains values from object and return them? [duplicate]检查数组是否包含来自对象的值并返回它们? [复制]
【发布时间】:2023-03-28 05:15:01
【问题描述】:

我有一个数组,这样说:

var array = [{something:"a"},{something:"b"},{something:"c"}]

我现在想要获取包含"b" 的对象。我该怎么做?

这是我之前尝试找到的内容:我发现 array.filterarray.findincludes 但我无法在 Object 内部的字符串上使用它一个数组,而不仅仅是数组中的字符串。

【问题讨论】:

  • array.find(x => x.something.includes("b")) 部分匹配或array.find(x => x.something === "b") 完全匹配。
  • filterfind 都将元素传递给回调函数。数组元素是您的对象,所以现在您需要做的就是访问该对象的特定属性。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 中的示例对 length 的作用,你想对 b 做。

标签: javascript arrays


【解决方案1】:

这将按照您的要求返回对象(如果它存在)

let resultWithSomethingB = array.filter(element => element.something === 'b')[0];

【讨论】:

  • 如果数组为空怎么办?
  • @nafas 结果将是undefined
  • @VLAZ 我以为这会抛出未定义的异常......我可能错了!!!
  • @nafas 过滤一个空数组会返回一个空数组。获取空数组的第一项返回undefined
【解决方案2】:

使用数组函数过滤器来完成这个:

var array = [{something:"a"},{something:"b"},{something:"c"}];

// Filter array based on .something
console.log(array.filter(a => { return a.something === "b" }))

【讨论】:

    【解决方案3】:

    在这种情况下你可以使用array.filter:

    let newObject = null;
    
    const newArray = array.filter(function(item) {
        // Return an item if the something property is a "b"
        return item.something === "b";
    });
    
    if (newArray.length > 0) {
        // Returns the first element
        newObject = newArray[0];
    }
    
    // Use the newObject
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      相关资源
      最近更新 更多