2017-03-10 63 views
0

因此,我不確定這裏發生了什麼,以及爲什麼要在JSON鍵名稱中輸入一段時間。從JSON響應中的鍵名稱中刪除句號

我想要做的事情的概述是通過ejs變量傳遞json響應到頁面模板中,並從個別字段中獲取數據。

JSON響應看起來是這樣的:

JSON tree

這是一個從prismic.io。 (打開對象支架被切斷,數據是主對象的子對象)。

當我通過EJS

<%= product.data.product.imgone2.value.main.url %> 

注入我得到這樣一個錯誤:

Cannot read property 'imgone2' of undefined 

哪,爲什麼會prismic做到這一點?

有沒有辦法解決與EJS內聯?

如果不是,我該如何解析JavaScript函數的JSON響應來移除它?

如果你需要我的路線:

router.get('/product/:slug', function(req, res) { 
//route params 
    var slug = req.params.slug; 
    var productResp; //scope up api response to pass to render() 
    console.log(slug); 
//api call 
    Prismic.api("https://prismic.io/api").then(function(api) { 
    return api.getByUID('product' , slug); 
    }).then(function(response) { 

    res.render('product-template', { 
     product: response, 
    }) 

    }, function(err) { 
    console.log("Something went wrong: ", err); 
    }); 
}); 

謝謝!

+4

您是否嘗試過'product.data [「product.imgone2」] .value.main.url'? – Hamms

+1

括號符號FTW! – epascarello

回答

2

您是否嘗試過product.data [「product.imgone2」] .value.main.url?

從官方文檔

要訪問像object.property

屬性的屬性必須是有效的JavaScript標識,即字母數字字符的序列,也包括下劃線(「_ 「)和美元符號(」$「),不能以數字開頭。例如,對象。$ 1是有效的,而object.1不是。

如果該屬性不是有效的JavaScript標識符,則必須使用括號表示法。

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Property_Accessors

0

因爲它已經提到,使用括號表示法:

product.data["product.imgone2"].value.main.url 

如果無法做到這一點無論出於什麼原因,你可以運行你的對象通過下面的函數來「修理」結構:

//this will transform structures like these: 
 
var a = { 
 
    "data": { 
 
    "product.imgone2": { 
 
     "value": { 
 
     "main.url": "yourMainUrl" 
 
     }, 
 
     "another.value": "to show how this is handled" 
 
    } 
 
    } 
 
} 
 

 
//into these: 
 
var b = nestKeysWithDots(a); 
 
console.log(JSON.stringify(b, null, 2)); 
 

 
//wich now can be resolved by your paths, without worrying 
 
console.log(
 
    "b.data.product.imgone2.value.main.url", 
 
    b.data.product.imgone2.value.main.url 
 
); 
 

 

 
//and the implementation: 
 
function isObject(value){ 
 
    return typeof value === "object" && value !== null; 
 
} 
 

 
function nestKeysWithDots(source){ 
 
    return !isObject(source)? source: 
 
    Array.isArray(source)? source.map(nestKeysWithDots): 
 
    Object.keys(source).reduce((target, path) => { 
 
     var value = nestKeysWithDots(source[path]); 
 
     path.split(".").reduce((obj, key, index, array) => { 
 
     if(index+1 === array.length){ 
 
      //last key 
 
      obj[key] = value; 
 
      return; 
 
     } 
 
     return key in obj && isObject(obj[key])? 
 
      obj[key]: 
 
      (obj[key] = {}); 
 
     }, target); 
 
     return target; 
 
    }, {}); 
 
}