【问题标题】:How to convert objects to array and save the id's from the objects如何将对象转换为数组并保存对象中的 id
【发布时间】:2022-01-03 01:27:30
【问题描述】:

我有一些问题,我试图解决一段时间但没有任何帮助,因为我在使用来自 API 的信息创建 div 时遇到了一些问题。

让我解释一下我到底有什么问题,然后是什么问题

firs:我从 cmc 获取 API 这是两个 url

     const bitcoinData = await fetch(`https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=${num}&limit=${numberOfCoins}&CMC_PRO_API_KEY=${apiKey.key}`)
    const bitcoinD = await bitcoinData.json()
    const bitcoinInfo = await fetch(`https://pro-api.coinmarketcap.com/v1/cryptocurrency/info?id=${array}&CMC_PRO_API_KEY=${apiKey.key}`)
    const bitcoinI = await bitcoinInfo.json()

*first 来自 api 的数组

*second 作为对象来自 api

第一个用于所有数据,第二个用于每个硬币的徽标图像,因为第一个 url 没有徽标,所以我需要将 url 徽标从第二个到第一个。一切正常,但是当我尝试在我的网站中搜索结果以查找带有过滤器和包含的硬币时,实际上它显示的信息最多,除了徽标,徽标始终保持在同一位置,但其余数据看起来很好。

-问题可能是无法对对象进行过滤...如果你们对我的问题有解决方案。

基本上我需要得到与第一个完全相同的第二个数组,但是数字的 id 将保持在外部并以相同的顺序,然后它解决了我的问题 像这样:

fromThis = {
1: {
    id: 825,
    name: "Tether",
    symbol: "USDT",
},
825: {
    id: 825,
    name: "Tether",
    symbol: "USDT",
},

toThis = [{
1: {
    id: 825,
    name: "Tether",
    symbol: "USDT",
},
825: {
    id: 825,
    name: "Tether",
    symbol: "USDT",
}]

但将 id 放在新数组的外面而不是里面

【问题讨论】:

  • toThis 语法无效,也许你希望 toThis = [ {1: { id: 825, name: "Tether", symbol: "USDT", }}, {825: { id: 825 , 名称: "Tether", 符号: "USDT", }}] 所以即使你的 fromthis 也不正确,它最后会漏掉 }
  • 是的,你说得对,你有正确语法的解决方案吗?

标签: javascript arrays search filter converters


【解决方案1】:

您的toThis 变量没有意义,您可以拥有一个对象数组,但是除非您更改变量的结构,否则您将无法拥有如上所述的id

您可以使用Map() 来实现这一目标,但是使用类似这样的东西:

const toThis = new Map();
for (const id in fromThis) {
    toThis.set(id, fromThis[id]);
}

// toThis map output
Map { 
    1: { id: 1, name: "Tether", symbol: "USDT" }, 
    825: { id: 825, name: "Tether", symbol: "USDT" }
 }

或者只是创建一个对象数组(但您将无法按照您指定的那样在对象之外获取id),方法是执行类似

const toThis = [];
for (const id in fromThis) {
    toThis.push(fromThis[id]);
}

// toThis array output
[ 
    { id: 1, name: "Tether", symbol: "USDT" }, 
    { id: 825, name: "Tether", symbol: "USDT" }
]

【讨论】:

    【解决方案2】:

    这不是有效的语法。

    const toThis = [
    1: {
        id: 825,
        name: "Tether",
        symbol: "USDT",
    },
    825: {
        id: 825,
        name: "Tether",
        symbol: "USDT",
    }]
    

    Uncaught SyntaxError: Unexpected token ':'

    你可以把对象放在一个数组中

    const toThis = [
    {
        id: 825,
        name: "Tether",
        symbol: "USDT",
    },
    {
        id: 825,
        name: "Tether",
        symbol: "USDT",
    }]
    
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多