【问题标题】:How to use .some() for all values in an array with different objects [duplicate]如何对具有不同对象的数组中的所有值使用 .some() [重复]
【发布时间】:2021-06-26 12:27:21
【问题描述】:

例如我有这个数组:

const ageArr = [{tom: 24}, {jack: 20}, {anna: 30}]

如何在不指定名称的情况下使用.some() 搜索所有值?

预期:

if (ageArr.some((el) => el > 19)) {
  console.log('Some of them are older than 19')
}
//Output: People are older than 19

【问题讨论】:

  • "...不指定名称?" - 使用更合适的对象/结构怎么样:{ name: "Tom", age: 24 } - 这样会更容易...
  • 我同意@Andreas。使用 Object.keys/values 提出的(当前)解决方案很麻烦,如果您的数据发生更改(例如,如果对象获得另一个属性),则很容易中断。使用合适的数据格式会更简洁,更不容易出错

标签: javascript


【解决方案1】:

您可以使用Object.values 函数来获取对象的值:

const ageArr = [{tom: 24}, {jack: 20}, {anna: 30}]

if (ageArr.some((el) => Object.values(el)[0] > 19)) {
  console.log('People are older than 19')
}

以下是Object.values 所做的一些示例:

[
  {tom: 24},
  {foo: 'bar', baz: 'qux'},
  {}
].forEach(x => console.log(`Object.values(${JSON.stringify(x)}) ==`, Object.values(x)))

【讨论】:

    【解决方案2】:

    @cherryblossom 使用函数Object.values 提供了解决此问题的最佳方法

    如果您担心浏览器兼容性,请记住,someObject.keys 函数甚至可以在 Internet Explorer 上运行,而 Object.values 则不能

    if (ageArr.some((el) => el[Object.keys(el)[0]] > 19)) {
      console.log('People are older than 19')
    }
    

    我会像这样扩展箭头函数:

    ageArr.some((el) => { 
        const key = Object.keys(el)[0];
        const value = el[key];
        return value > 19;
    }
    

    【讨论】:

    • 很容易填充那些不可用的方法。并且箭头函数在 IE 中不起作用
    • 你是对的,箭头功能在IE中不可用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多