0

I want to map one array on to another and if they match then display the value from the second

Here is my code;

let carMakes = ["ford", "volvo", "tesla", "BMW"];

let carMakeStrings = {
  ford: "Ford Motor Company",
  volvo: "Volvo Cars",
  tesla: "S3XY",
  BMW: "BMW",
  GM: "General Motors",
  Jaguar: "Jaguar",
  AlfaRomeo: "Fiat Chrysler Automobiles"
}

return (
    <div>
        <ul>
            {carMakes.map((carMake, key) => {
                return (
                    <li
                        key={key}
                    >
                        {carMake === carMakeStrings ? (carMakeStrings.value):("")}
                    </li>)
            })}
        </ul>
    </div>
)

What I want to display is an unordered list of 4 items like this

  • Ford Motor Company
  • Volvo Cars
  • S3XY
  • BMW

Currently I think I'm completely off with this solution but I'm not sure what to research - if someone can at least point me in the correct direction of what I should be researching that would be very appreciated

1
  • Are the carMakes entries guaranteed to be present in the carMakeStrings array? Commented Nov 13, 2020 at 14:36

2 Answers 2

2

You can check with this condition carMakeStrings[carMake] to check whether it exists or not:

return (
    <div>
        <ul>
            {carMakes.map((carMake, key) => {
                return carMakeStrings[carMake] && (
                    <li key={key}>
                        {carMakeStrings[carMake]}
                    </li>)
            })}
        </ul>
    </div>
)
Sign up to request clarification or add additional context in comments.

Comments

0

You just need to use bracket notation to look up the carMake property on the object:

const App = () => {
  let carMakes = ["ford", "volvo", "tesla", "BMW"];

  let carMakeStrings = {
    ford: "Ford Motor Company",
    volvo: "Volvo Cars",
    tesla: "S3XY",
    BMW: "BMW",
    GM: "General Motors",
    Jaguar: "Jaguar",
    AlfaRomeo: "Fiat Chrysler Automobiles"
  }

  return (
      <div>
          <ul>
              {carMakes.map((carMake, key) => (<li key={key}>{carMakeStrings[carMake]}</li>))}
          </ul>
      </div>
  )
};
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class="react"></div>

Comments

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.