1

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?

1
  • 2
    It works fine, except you'll get errors for those keys in bag that aren't in your assetList. You're not using anything in bag other than the keys so why not map through the keys/values of assetList instead> Commented Dec 26, 2021 at 13:26

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

lol. You're welcome. I'm glad that your n00bness is saved :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.