Home > Software engineering >  Mixing 2 objects in react
Mixing 2 objects in react

Time:12-27

I've got 2 objects:

const bag = { eth: 50, btc: 30, kla: 10, set: 5, ova: 5 };
const assetList = {
  eth: {
    name: "Ethereum",
    icon: "urlhere",
    colour: "#030",
    text: "light",
  },
  btc: {
    name: "Bitcoin",
    icon: "urlhere",
    colour: "#000",
    text: "dark",
  },
};

Now I would like to end up with:

    <ul>
      {Object.keys(bag).map(function (asset, keyIndex) {
        return (
          <li>
            {assetList[asset].name}
          </li>
        );
      })}
    </ul>

I'm trying to approach this as I would in python, but this clearly doesn't work. How can I get the name of the responding assets here?

CodePudding user response:

Use a ternary to and check if the asset exists in the assetList. If not return null instead.

const Demo = ({ bag, assetList }) => (    
  <ul>
    {Object.keys(bag).map(asset => assetList[asset] ? (
      <li key={asset}>
        {assetList[asset].name}
      </li>
    ) : null)}
  </ul>
);

const bag = { eth: 50, btc: 30, kla: 10, set: 5, ova: 5 };
const assetList = {"eth":{"name":"Ethereum","icon":"urlhere","colour":"#030","text":"light"},"btc":{"name":"Bitcoin","icon":"urlhere","colour":"#000","text":"dark"}};

ReactDOM.render(
  <Demo bag={bag} assetList={assetList} />,
  root
);
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

  • Related