【问题标题】:Retrieve only the column of a javascript array仅检索 javascript 数组的列
【发布时间】:2021-03-10 03:39:09
【问题描述】:

执行 Sql 查询后,我有一个如下所示的数组。 我想以名称如下所示的方式仅检索“名称”列:“名称1,名称2,名称3”。 我不知道如何做到这一点,我在互联网上查看,但我没有找到任何结论。 您知道如何从“名称”列中检索所有数据吗? 提前谢谢你。

Array =
[1] {
    id_idx: 1,
    hero_order: 0,
    name: 'Nom1'
},
[2] {
    id_idx: 1,
    hero_order: 0,
    name: 'Nom2'
},
[3]  {
    id_idx: 1,
    hero_order: 0,
    name: 'Nom3'
}

我忘记了一个信息:该数组来自一个 SQL 查询 rows2[].name.

【问题讨论】:

  • let result=array.map(data=>data.name)

标签: javascript arrays discord.js


【解决方案1】:

您可以在任何 JavaScript 数组上使用 map 函数,文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

基本上,映射函数将类型“A”转换为类型“B”。 在你的情况下,你想从类型:

Array<{
    id_idx: number,
    hero_order: number,
    name: string
}>

收件人:

Array<string>

这可以通过 map 函数来完成,如下所示:

const names = myArray.map(a => a.name);

【讨论】:

    【解决方案2】:

    以下代码应该会给你一个可行的解决方案 -

    const result = [{
        id_idx: 1,
        hero_order: 0,
        name: 'Nom1'
    },
    {
        id_idx: 1,
        hero_order: 0,
        name: 'Nom2'
    },
    {
        id_idx: 1,
        hero_order: 0,
        name: 'Nom3'
    }]
    
    const outputArray = result.map((singleResult) => singleResult.name);
    
    const outputString = outputArray.join(",");
    
    console.log("This will give you an array as output - " + outputArray);
    
    console.log("This will give you string as a output - " + outputString);
    
    console.log('outputArray type:' + typeof outputArray);
    
    console.log('outputString type:' + typeof outputString);

    【讨论】:

      【解决方案3】:

      感谢您的帮助。

      很遗憾,这并没有解决我的问题。

      我忘记了一个信息:该数组来自一个 SQL 查询 rows2[].name.

      我尝试使用地图,但这是我看到的错误 Visual code TypeError: Cannot read property 'map' of undefined

                 const result = rows2;
                 const outputArray = result.map((singleResult) => singleResult.name);
                 const outputString = outputArray.join(",");
                 const names = rows2.map(a => a.name);
      
                 console.log(names);
      

      【讨论】:

      • rows2 不是数组而是其他类型,尝试控制台记录它并查看它的外观。它可能是一个对象或类似的东西?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      • 2021-01-28
      • 2016-01-23
      • 2021-10-22
      相关资源
      最近更新 更多