【问题标题】:How to fetch multiple key-value pairs array in Java Script/TestCafe如何在 Java Script/TestCafe 中获取多个键值对数组
【发布时间】:2020-11-28 09:59:30
【问题描述】:
const passnegerGroup = [
  { FIRSTNAME: 'RAHUL', LASTNAME: 'KUMAR' },
  { FIRSTNAME: 'RINA', LASTNAME: 'KUMAR' },
  { FIRSTNAME: 'SOHAN', LASTNAME: 'SINGH' },
  { FIRSTNAME: 'PAUL', LASTNAME: 'ANDERSON' },
];

// I want to read each passenger's last name and first name and do some operations.

// Tried this code but this is

for (const key of Object.values(passnegerGroup)) {
  console.log(key.FIRSTNAME, key.LASTNAME);
}

输出:

拉胡尔·库马尔 丽娜·库马尔 索汉·辛格 保罗·安德森

这适用于但出现 ESLINT 错误。 ESLint: iterators/generators require regenerator-runtime,这对于本指南来说太重了,不允许他们使用。另外,应避免循环以支持数组迭代。 (无限制语法)

请帮助我使用一些现代 JavaScript/TestCafe 代码实现上述目标。

【问题讨论】:

    标签: javascript testing automated-tests testcafe keyvaluepair


    【解决方案1】:

    const passnegerGroup = [
      { FIRSTNAME: 'RAHUL', LASTNAME: 'KUMAR' },
      { FIRSTNAME: 'RINA', LASTNAME: 'KUMAR' },
      { FIRSTNAME: 'SOHAN', LASTNAME: 'SINGH' },
      { FIRSTNAME: 'PAUL', LASTNAME: 'ANDERSON' },
    ];
    
    //No garantee that firstname comes before lastname
    const result1 = passnegerGroup.map( u => Object.values(u) ).flat().join(' ');
    console.log(result1);
    
    const result2 = passnegerGroup.map( u => [u.FIRSTNAME, u.LASTNAME]).flat().join(' ');
    console.log(result2);

    【讨论】:

    • 感谢您的快速解决方案。它对我有用。虽然我不需要加入,所以我一直使用到 passnegerGroup.map(u => Object.values(u)) 并且它有效。我会接受的。
    • 它可以工作,但它的转换过度。最好更明确的输出 - 使用reduce方法而不是map,因为它返回一个数组,然后需要进一步格式化。
    • 是的,你是对的,显然没有优化。 @shashankshekhar,如果您使用的是 20Mhz cpu,那么在 4 大小的阵列上使用这种 3chained 方法完全是矫枉过正哈哈
    • 更多的是关于理解的步骤。 Map 方法返回一个数组,但你想要一个字符串。纯编程原理。
    【解决方案2】:

    const passnegerGroup = [
      { FIRSTNAME: 'RAHUL', LASTNAME: 'KUMAR' },
      { FIRSTNAME: 'RINA', LASTNAME: 'KUMAR' },
      { FIRSTNAME: 'SOHAN', LASTNAME: 'SINGH' },
      { FIRSTNAME: 'PAUL', LASTNAME: 'ANDERSON' },
    ];
    
    const result = passnegerGroup.reduce((accum, cur) => `${accum} ${cur.FIRSTNAME} ${cur.LASTNAME} `, '');
    
    console.log('result =', result);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多