如何单独获取和调用所有值.这里没有数组的名称,所以我如何访问它


{
"amazon": "",
"flipkart": "",
"snapdeal": "",
"ebay": "",
"paytm": "",
"croma": "",
"yebhi": "",
"indiatimes": "",
"homeshop18": "",
"naaptol": "",
"infibeam": "",
"tatacliq": "",
"shopclues": "",
"paytmmall": "",
"gadgets360": ""
}

这是我的代码:

function fetchProduct(){
    console.log(pro_input.value)
    fetch('https://price-api.datayuge.com/api/v1/compare/price? 
    api_key=...&id='+pro_input.value+'')
      .then(response =>{
          if(! response.ok){
            throw Error("Error");
          }
          return response.json();
      })
      .then(data =>{
        const html2 = data(product_comp =>{
          return `<div class = "product_list">
                    <div class ="pro_comparedprice">
                      <p>Amazon: ${product_comp.amazon}</p>
                      <p>flipkart: ${product_comp.flipkart}</p>
                      <p>snapdeal: ${product_comp.snapdeal}</p>
                      <p>ebay: ${product_comp.ebay}</p>
                      <p>paytm: ${product_comp.paytm}</p>
                      <p>croma: ${product_comp.croma}</p>
                      <p>yebhi: ${product_comp.yebhi}</p>
                      <p>indiatimes: ${product_comp.indiatimes}</p>
                      <p>homeshop18: ${product_comp.homeshop18}</p>
                      <p>naaptol: ${product_comp.naaptol}</p>
                      <p>infibeam: ${product_comp.infibeam}</p>
                      <p>tatacliq: ${product_comp.tatacliq}</p>
                      <p>shopclues: ${product_comp.shopclues}</p>
                      <p>paytmmall: ${product_comp.paytmmall}</p>
                      <p>gadgets360: ${product_comp.gadgets360}</p>
                    </div>
                  </div>`
        }).join("");
        console.log(html2);
        document.querySelector("#pro_comparedprice").insertAdjacentHTML('afterbegin',html2);
      })
      .catch(error =>{
        console.log(error);
      });
  }

在javascript中,如果您想获取数组X的数据,我们使用X.forEach(),如:

X.forEach((item,index)=>{
   /*instructions*/
})

但对于非数组对象,这有点不同
这里我们使用Object.keys(X),它将在一维数组中返回一个具有X对象所有属性的数组(我们将其命名为arr(
现在我们可以使用一个简单的for循环来单独获取和调用每个值:

let arr = Object.keys(X)
for(var i=0; i<arr.length; i++){
   X[arr[i]]
}

最新更新