reactjs 如何进入对象内部/JSON - React Next.JS -对象内部ID(对象)

oxiaedzo  于 2022-12-12  发布在  React
关注(0)|答案(2)|浏览(118)

我的JSON是这样的:

{
   "quoteId":"7ab6cb9f-f1a9-4484-aee7-686ba6f7e7a8",
   "groups":{
      "group1":{
         "pickup":{
            
         },
         "pickupExceptions":[
            
         ],
         "shipment":{
            "20b65e13-629b-4a40-8586-04360c4fdb18":{
               "id":"20b65e13-629b-4a40-8586-04360c4fdb18",
               "method":"Economics",
               "methodId":"123",
               "price":192.58
            }
         }
      }
   }
}

〈--旁边的shiment prop --〉这个 prop ,每次召唤都换!--〉
我尝试了不同的方法,但无法访问de prop:价格:
这是最后一次尝试...

<span>QuoteId: {quotationData}</span> <br />
            <br />
   {quotationDataComplete.map((quote) => (
              <div className={styles.card} key={quote.groups.group1.shipment}>
                <span>Price: {quote.price}</span> <br />
                   <br />
              </div>
            ))}

我试着这样

<div className={styles.card} 
key={quote.groups.group1.shipment}>
key={quote.shipment}>
<span>Price: {quote.price}</span> <br />
<span>Price: {quote.groups.group1.shipment}</span> <br />
<span>Price: {quote.shipment.price}</span> <br />

没有人工作

7y4bm7vi

7y4bm7vi1#

你可以这样做:

const quote = {
   "quoteId":"7ab6cb9f-f1a9-4484-aee7-686ba6f7e7a8",
   "groups":{
      "group1":{
         "pickup":{
            
         },
         "pickupExceptions":[
            
         ],
         "shipment":{
            "20b65e13-629b-4a40-8586-04360c4fdb18":{
               "id":"20b65e13-629b-4a40-8586-04360c4fdb18",
               "method":"Economics",
               "methodId":"123",
               "price":192.58
            }
         }
      }
   }
}

let shipment = quote.groups.group1.shipment;
// Now as `shipment` still is an object, you need to traverse it further
shipment = Object.values(shipment)[0];

console.log('Price:',shipment.price)
// Result
// Price: 192.58

我们可以这样做一行:

const shipment = Object.values(quote.groups.group1.shipment)[0];

console.log('Price:',shipment.price)
ijnw1ujt

ijnw1ujt2#

如果它是实际的JSON,而不仅仅是Javascript中的类似JSON的结构,您将需要解析它JSON.parse(jsonString);如果它在单独的文件中,您将需要首先读取该文件,您可以通过let quote = require('quote.json')完成此操作
然后,您可以像使用其他对象一样使用它作为完整的Javascript对象。如果它已经在内存中,您将不需要执行request,但下面的代码仍然是相同的。

<div className={styles.card} 
key={quote.groups.group1.shipment}>
key={quote.shipment}>
<span>Price: {Object.values(quote.groups.group1.shipment)[0].price}</span> <br />

不过,我会假设与方式,这是设置你实际上会想循环思想他们。
所以你会想要更像

<div>
    {quote.groups.group1.shipment.map( (val, guid) => {
        return (
            <div className={style.card} key={quote.groups.group1.shipment[guid].price}>
                <span>Price: {Object.values(quote.groups.group1.shipment)[0].price}</span>
            </div>
    </div>
        )
    }
</div>

相关问题