2013-03-16 31 views
0
格式化

您好,我目前正在运行在我的JavaScript函数称为“保存”,其具有的功能:更改在Javascript

function save(){ 

var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || []; 

var newItem = {}; 
var num = document.getElementById("num").value; 

newItem[num] = { 
    "methv": document.getElementById("methv").value 
    ,'q1': document.getElementById("q1").value, 
    'q2':document.getElementById("q2").value, 
    'q3':document.getElementById("q3").value, 
    'q4':document.getElementById("q4").value, 
    'comm':document.getElementById("comm").value 
}; 


oldItems.push(newItem); 

localStorage.setItem('itemsArray', JSON.stringify(oldItems)); 

,目前的这个格式出来是这样的:

[{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}] 

有什么办法,我可以将它更改为一个格式是这样的:

{1173627548,不知道, - , - ,U, - ,} 感谢

+0

当然,你可以把它写这样的,但这不会再被JSON。你会如何解析它? – 2013-03-16 16:03:45

+0

所以你想剥离属性名称,结构和引号?正如提到的那样,这不是JSON,如果格式发生变化,您将无法从中取回数据。你也不会写任何有逗号的东西,而不会以某种方式逃脱。如果你想这样做,你也可以用自己的函数来编写字符串。 – Dave 2013-03-16 16:06:35

回答

1

所有您需要做的是使用,而不是一个对象数组:

newItem = [ 
    num, 
    document.getElementById('methv').value, 
    document.getElementById('q1').value, 
    document.getElementById('q2').value, 
    document.getElementById('q3').value, 
    document.getElementById('q4').value, 
    document.getElementById('comm').value 
];