-2
對不起,我是JS的noob。我有字符串:JS將字符串轉換爲數組
[{"priceEm": 28000, "priceId": "25094967"}]
我怎樣才能在轉換爲數組
['priceEm': 28000, 'priceId':'25094967']
並反覆通數組,而不是直通線
對不起,我是JS的noob。我有字符串:JS將字符串轉換爲數組
[{"priceEm": 28000, "priceId": "25094967"}]
我怎樣才能在轉換爲數組
['priceEm': 28000, 'priceId':'25094967']
並反覆通數組,而不是直通線
生成與字符串作爲HTML內容臨時DOM元素(由設置innerHTML
屬性),最後得到textContent
這將是解碼數據。
var str = '[{"priceEm": 28000, "priceId": "25094967"}]';
// create a temporary div element
var temp = document.createElement('div');
// set the html content
temp.innerHTML = str;
// get the text content
console.log(temp.textContent);
或用textarea
做同樣的,並得到value
最後。
var str = '[{"priceEm": 28000, "priceId": "25094967"}]';
// generate a temporary textarea
var temp = document.createElement('textarea');
// set the html content
temp.innerHTML = str;
// get the value of the element
console.log(temp.value);
UPDATE:結果是有效的JSON數據,你可以使用JSON.parse
方法傳遞JSON字符串後迭代。
var str = '[{"priceEm": 28000, "priceId": "25094967"}]';
var temp = document.createElement('textarea');
temp.innerHTML = str;
// parse the JSON string
var arr = JSON.parse(temp.value);
console.log(arr[0]);
// iterate over the array
arr.forEach(function(obj) {
console.log(obj);
// iterate over the object properties
Object.keys(obj).forEach(function(k) {
console.log(k, obj[k]);
})
});
Pranav的答案是接近。您需要將其解析爲最終訪問其屬性的對象:
var str = '[{"priceEm": 28000, "priceId": "25094967"}]';
var temp = document.createElement('div');
temp.innerHTML = str;
var finalObj = JSON.parse(temp.textContent)[0];