代码之家  ›  专栏  ›  技术社区  ›  infodev

在JS中对JSON数组使用find方法时只发送键值

  •  0
  • infodev  · 技术社区  · 7 年前

    我将从JSON数组中获得一个值,因此我使用 find 方法:

    let actualElm = this.initialData.find(elm => {
      if (elm.identifiant == this.actualId) {
        return elm.country;
      }
    });
    

    问题在于 找到 是返回所有对象( elm 对象)我只会得到 elm.country .

    我该怎么办?

    4 回复  |  直到 7 年前
        1
  •  6
  •   Zenoo    7 年前

    你可以简化你的 Array#find 函数和调用 .country 后:

    let actualElm = this.initialData.find(elm => elm.identifiant == this.actualId).country;
    

    如果你 find() 在您的情况下可能会失败,请添加一个故障保护 (... || {}) :

    let actualElm = (this.initialData.find(elm => elm.identifiant == this.actualId) || {}).country;
    
        2
  •  3
  •   makmonty    7 年前

    这个 find 方法扫描数组,并在提供的函数返回Truthy值时返回数组的一个元素。在您的示例中,当 if 条件为真,它将选择该元素并返回它。

    您可以这样做:

    let elm = this.initialData.find(elm => elm.identifiant == this.actualId);
    let actualElm = (elm || {}).country;
    

    通知查找可以返回 undefined 如果没有找到元素,那么我必须检查它是否存在。

        3
  •  2
  •   cymruu    7 年前

    find接受一个返回布尔值的函数,该函数确定当前元素是否符合给定条件。如果为真,则返回整个元素。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

    你可以用前臂实现你想要的

        4
  •  2
  •   Robby Cornelissen    7 年前

    这些是 Array.prototype.find() . 它将返回回调函数计算为的第一个元素 truthy 价值。在您的示例中,回调方法返回 country 属性,它是 诚实的 但这并不能改变 find() 仍然会返回完整的对象。

    如果你保证找到一个结果,你可以做以下的事情:

    let country = this.initialData.find(e => e.identifiant == this.actualId).country;