简体   繁体   English

映射对象数组 React

[英]Mapping Array of Objects React

So I am currently having a little problem here.所以我目前在这里遇到了一个小问题。 So I have this Component that is taking data from JSON, I have Link but is showing the like 20 times more.所以我有这个组件,它从 JSON 获取数据,我有链接,但显示的次数是 20 倍。 The same amount of objects that I have in JSON file.我在 JSON 文件中拥有相同数量的对象。 I know this is the problem {data.map((postData) , it is mapping all the objects in JSON file, when I want that the only ( classE , priceE and imageE ) to show.我知道这是问题{data.map((postData) ,它正在映射 JSON 文件中的所有对象,当我想要唯一的( classEpriceEimageE )显示时。


import React from "react";
import data from "./data.json";
import { Link } from "react-router-dom";
function E() {
  return (
    <div>
      {data.map((postData) => {
        return (
          <div key={postData.id} className="m-4 bg-blue-100 rounded-xl p-8 ">
            <div>
              <Link
                to={`/payment/${postData.id}`}
                className="py-1 px-2 text-black-600 h-10  ml-24 mt-32 bg-white w- 
            36 rounded-full focus:outline-none focus:ring-2 focus:ring-gray-600"
              >
                Buy Now
              </Link>
              <img
                alt=""
                className="w-screen object-contain"
                src={postData.imageE}
              ></img>
              <h1 className=" ml-24 md:text-5xl sm:text-5xl  top-8">
                {postData.classE}
              </h1>
              <h1 className="text-base font-mono ml-24 top-24">
                {postData.priceE}
              </h1>
            </div>
          </div>
        );
      })}
    </div>
  );
}

export default E;

JSON file JSON 文件

[
  {
    "id": 0,
    "class": "A-Class",
    "Info": "A is the cheapest one ",
    "imageA": "./ModImages/Aclass.jpg",
    "textA": "fdsd",
    "trefuA": "fdsd",
    "optionA": "fdsd"
  },
  {
    "id": 1,
    "classE": "E-Class",
    "imageE": "./ModImages/Eclass.jpg",
    "priceE": "$43,600"
  }
]

Try this:尝试这个:

{data.filter(d =>
  d.classE &&
  d.imageE &&
  d.priceE) //FILTER FIRST
  .map((postData) => { //THEN MAP
  //CODE HERE
  })
}

You filter the data first, then you map it你先过滤数据,然后你 map 它

If you want to display only the objects with the properties classE , imageE , and priceE , you need to filter out the objects you are not interested in.如果您只想显示具有classEimageEpriceE属性的对象,则需要过滤掉您不感兴趣的对象。

Change this line:更改此行:

{data.map((postData) => {

to:至:

{data.filter(d =>
  d.hasOwnProperty('classE') &&
  d.hasOwnProperty('imageE') &&
  d.hasOwnProperty('priceE'))
  .map((postData) => {

That will display only the objects you want.这将只显示您想要的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM