Kazi Arifin Islam
Kazi Arifin Islam

Reputation: 11

Extract values with similar JSON data in REACT

I have got a JSON file like this:

[
  {
    "symbol": "A",
    "name": "Agilent Technologies Inc",
    "exchange": "NYSE",
  },
  {
    "symbol": "AACG",
    "name": "ATA Creativity Global",
    "exchange": "NASDAQ",
  },
  {
    "symbol": "AA",
    "name": "Alcoa Corp",
    "exchange": "NYSE",
  },
  {
    "symbol": "AAA",
    "name": "AXS FIRST PRIORITY CLO BOND ETF ",
    "exchange": "NYSE",
  },
{ "symbol": "AAP",
    "name": "AXS FIRST PRIORITY CLO BOND ETF ",
    "exchange": "NASDAQ",}...]

And a dropdown with NYSE & NASDAQ. I want to implement that when I select NYSE or NASDAQ exchange, the name & symbol associated with this exchange. I've tried something like this

const Dropdown = () => {
  const [exchange, setExchange] = useState([]);
  const [select, setSelect] = useState([]);
  //   let mySet = new Set();
  //   mySet.add(Records.map((record) => record.exchange));
  //   console.log(mySet);
  let chars = Records.map((record) => record.exchange);
  let UniqueChars = [...new Set(chars)];
  // console.log(UniqueChars);
  const showStocks = (event) => {
    const current = event.target.value;
    const names = Records.filter((record) => {
      return <h3>{record.exchange.includes(current)}</h3>;
    }).map((x) => x.name);
    if (current === "") {
      setExchange([]);
    } else {
      setExchange(names);
      setSelect(current);
    }
    // console.log(names);
  };

  return (
    <div>
      {/* <label>Choose a Exchange:</label> */}

      <select
        name="exchanges"
        id="exchanges"
        value={select}
        onChange={showStocks}
      >
        <option selected="selected" disabled="disabled" value={exchange}>
          Choose an Exchange
        </option>
        {UniqueChars.map((record, key) => {
          // console.log(record);
          return (
            <option
              className="dataItem"
              key={key}
              value={record}
              // onClick={showStocks}
              // option={showStocks}
              //   onClick={() => getData(record.symbol)}
            >
              {record}
              {/* {(record = "NYSE" ? setExchange(record.symbol) : record)} */}
            </option>
          );
        })}
      </select>
      {exchange}
    </div>
  );
};

it's showing all the names in the JSON file. Not showing the specific Exchange containing stock names. It's not working apparently. There may be some mistakes with my logic. I can't implement itenter image description here

Upvotes: 1

Views: 71

Answers (1)

lehanh
lehanh

Reputation: 585

You are using native select which only allow string value. You are passing list of object. You should change the name to this:

const names = Records.filter((record) => {
   return <h3>{record.exchange}</h3>;
 }).map(x => x.name);

Upvotes: 1

Related Questions