【问题标题】:Mapping data from Object of Objects in React在 React 中从 Object of Objects 映射数据
【发布时间】:2023-03-27 12:04:01
【问题描述】:

我正在从 api 获取一些数据,我想通过它进行映射,以便获取里面的所有值。但我无法这样做。需要一些帮助。 这是数据:

{
'id:5': {
    1: {
        coinid: 5,
        coinname: 'Chainlink',
        publishedAt: '2021-06-24T11:10:54Z',
        source: 'Cointelegraph',
        title:
            'asset manager qr launches bitcoin etf on brazilian stock exchange',
        description:
            'in contrast to hashdexs crypto etf product qr asset managements product provides exposure to bitcoin exclusively',
        url: 'https://cointelegraph.com/news/asset-manager-qr-launches-bitcoin-etf-on-brazilian-stock-exchange',
    },
    2: {
        coinid: 5,
        coinname: 'Chainlink',
        publishedAt: '2021-06-24T13:39:56Z',
        source: 'Business Wire',
        title:
            'truefi announces new integrations with binance chainlink and sushiswap further embedding into the defi ecosystem',
        description:
            'san franciscobusiness wire binancetrusttoken announces a suite of deep defi integrations designed to make the truefi platform safer more robust and more lucrative for its users',
        url: 'https://www.businesswire.com/news/home/20210624005642/en/TrueFi-Announces-New-Integrations-With-Bina',
    },
}

这是我获取 api 的代码(我必须对 api 数据进行转义,因为它是转义形式):

    const fetchNews = async () => {
    try {
        const { data } = await axios.get(
            'https://h3iiccq04i.execute-api.ap-south-1.amazonaws.com/dev',
        );
        console.log(JSON.parse(data));
        // setNewsData(JSON.parse(data));
        setLoading(false);
    } catch (err) {
        console.log(err.message);
    }
};

这里的 newsData 是一个对象,我必须映射并获取所有值,例如 coinname 、 url 等。任何帮助将不胜感激。

【问题讨论】:

  • {Object.values(newsData["id:5"]).map(...)} (您的实际问题是:“如何以数组形式获取对象的值?”)

标签: javascript json reactjs amazon-web-services axios


【解决方案1】:

我们可以使用Object.values() 获取包含所有对象值的数组,然后使用映射对其进行迭代。

const dataArray = Object.values(data['id:5'])
dataArray.map(...)

【讨论】:

    猜你喜欢
    • 2018-02-15
    • 2018-10-19
    • 2020-10-10
    • 1970-01-01
    • 2021-03-25
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    相关资源
    最近更新 更多