lucascosta
lucascosta

Reputation: 21

How can i access data from a array of objects in json with reactjs

i have an array of objects in json and i want to pull only specific data from it, how can i do that?

heres my files:

import Stocks from "./stocks.json";

export default function Profile() {
  return (
    <>
      <h1>{Stocks.symbol}</h1>
      <h1>{Stocks.lastsale}</h1>
    </>
  );
}

and stocks.json

{
      "symbol": "AAMC",
      "name": "Altisource Asset Management Corp Com",
      "lastsale": "$36.38",
      "netchange": "0.88",
      "pctchange": "2.479%",
      "volume": "11317",
      "marketCap": "64654718.00",
      "country": "United States",
      "ipoyear": "",
      "industry": "Investment Managers",
      "sector": "Finance",
      "url": "/market-activity/stocks/aamc"
    }

https://codesandbox.io/s/distracted-leftpad-ve6ch0?file=/App.js

this way above it works perfectly, the problem is that i want to have multiple objects inside the json file, as follow:

[
  {
      "symbol": "AAMC",
      "name": "Altisource Asset Management Corp Com",
      "lastsale": "$36.38",
      "netchange": "0.88",
      "pctchange": "2.479%",
      "volume": "11317",
      "marketCap": "64654718.00",
      "country": "United States",
      "ipoyear": "",
      "industry": "Investment Managers",
      "sector": "Finance",
      "url": "/market-activity/stocks/aamc"
    },
    {
      "symbol": "AAU",
      "name": "Almaden Minerals Ltd. Common Shares",
      "lastsale": "$0.2167",
      "netchange": "-0.0036",
      "pctchange": "-1.634%",
      "volume": "196889",
      "marketCap": "29735879.00",
      "country": "Canada",
      "ipoyear": "2015",
      "industry": "",
      "sector": "",
      "url": "/market-activity/stocks/aau"
    }
  ]

my objective is to pull the data from a specific stock, like the "lastsale" for example

thanks in advance! in kinda new to programming

i want to be able, to pull only the data from a specific stock, like using the AMMC symbol as a input to get the "lastsale" from it

Upvotes: 2

Views: 44

Answers (1)

Fernando Montoya
Fernando Montoya

Reputation: 2644

You would need to find your desired stock using array search methods like, .find, .findIndex or just .filter.

In this specific case you can use:

const AAMCStock = Stocks.find(stock => stock.symbol === "AAMC")
const lastSale = AAAMStock.lastsale

You can find more information about this method here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Upvotes: 3

Related Questions