将JSON对象转换为数组并保留索引

5f0d552i  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(115)

大家好,这里有点困难。我正在从POST API接收数据,并试图使用这些数据来解析和更新后端MongoDB。我正在接收数据,但似乎无法正确解析它。

{
    "0xa0cC4414019471bef0fe0b07a76dA1F7CDc4cCf7": {
        "0x6f5dabb430572370d63010e5d6a52e39f40e73751e8d49f3e0088d6b76a5dc53": {
            "chain": "bsc",
            "soldAmount": 77.91952132935356,
            "boughtAmount": 7581.592038,
            "basePrice": 0.010277461638506796,
            "usdPrice": 0.010277461638506796,
            "usdSpent": 77.91952132935356,
            "walletAddress": "0x06f74D2dB8bFbeD7bFa3f809f01D7ad4bdaCd0D0",
            "whale": false
        }
    },
    "0x81cAd0ab645A1792F585cE93c5f955Ff3eCC3951": {
        "0x58601dd284313e72c70987774129659f0f3327354e03dad820ff498ac2bcd980": {
            "chain": "bsc",
            "soldAmount": 0.04130355997068365,
            "boughtAmount": 12006668.37444406,
            "basePrice": 3.4400517014859345e-09,
            "usdPrice": 1.1540347696736513e-06,
            "usdSpent": 13.856112772049464,
            "walletAddress": "0x52739B1646EBE3879C2592686D10094a3f88D3Aa",
            "whale": false
        }
    }
}

我需要保持这两个关键字开始与0x,但每当我格式化它我失去了这些关键字的价值,或不能得到到第三级下来。
目标是使用这些项中的每一项对函数运行。
最酷的将是有一个新的阵列与所有项目在一个。
任何帮助都是感激。下面是我目前的代码。

var importData = req.body;

var txsData = [];

for (let [tx, value] of Object.entries(importData)) {
    txsData.push([tx, value])
  }
zhte4eai

zhte4eai1#

根据我的理解,你正在尝试将所有以0x开头的键(也是嵌套的)存储在一个单独的数组中。

const jsonObj = {
  "0xa0cC4414019471bef0fe0b07a76dA1F7CDc4cCf7": {
    "0x6f5dabb430572370d63010e5d6a52e39f40e73751e8d49f3e0088d6b76a5dc53": {
      "chain": "bsc",
      "soldAmount": 77.91952132935356,
      "boughtAmount": 7581.592038,
      "basePrice": 0.010277461638506796,
      "usdPrice": 0.010277461638506796,
      "usdSpent": 77.91952132935356,
      "walletAddress": "0x06f74D2dB8bFbeD7bFa3f809f01D7ad4bdaCd0D0",
      "whale": false
    }
  },
  "0x81cAd0ab645A1792F585cE93c5f955Ff3eCC3951": {
    "0x58601dd284313e72c70987774129659f0f3327354e03dad820ff498ac2bcd980": {
      "chain": "bsc",
      "soldAmount": 0.04130355997068365,
      "boughtAmount": 12006668.37444406,
      "basePrice": 3.4400517014859345e-09,
      "usdPrice": 1.1540347696736513e-06,
      "usdSpent": 13.856112772049464,
      "walletAddress": "0x52739B1646EBE3879C2592686D10094a3f88D3Aa",
      "whale": false
    }
  }
};

const res = [];

function getKeys(obj) {
  Object.keys(obj).forEach(key => {
    if (key.startsWith('0x')) res.push(key);
    if (typeof obj[key] === 'object') {
        getKeys(obj[key])
    }
  })
}

getKeys(jsonObj);
console.log(res);

相关问题