0

Вопрос заключается в получении значения, из массива вложенных объектов. Я хочу заменить вот эту строку <p>{current.car[0].model}</p>,на более динамическую, что бы отображались все значения model, которые есть у вложенных объектов массива car. Если же введу просто <p>{current.car.model}</p> то ничего не отображается на странице, так как выдает в консоли undefined

import logo from "./logo.svg";
import "./App.css";
import { useState } from "react";

function App() {
  const fakeDB = [
    {
      id: "1",
      name: "Carl",
      age: 45,
      height: 170,
      car: [
        {
          id: "2",
          model: "mazda",
          color: "blue",
        },
        {
          id: "3",
          model: "toyota",
          color: "black",
        },
      ],
    },
  ];

  return (
    <div>
      {fakeDB.map((current, key) => {
        return (
          <div>
            <p>{current.name}</p>
            <p>{current.car[0].model}</p>
          </div>
        );
      })}
    </div>
  );
}

export default App;
0

1 ответ 1

1
const arr = []
 fakeDB[0].car.forEach((item) => arr.push(item.model))  // вытаскиваем все значения по ключу model из вложенных в массив car обьектов

const result = arr.map(item =>  `<p> ${item}<p>`)
console.log(result)  // ["<p> mazda<p>", "<p> toyota<p>"]

можно так.

1

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.