【问题标题】:Outputs local storage object with Square and Curly brackets when parsing JSON object解析 JSON 对象时输出带有方括号和大括号的本地存储对象
【发布时间】:2020-12-21 23:11:33
【问题描述】:

制作一个简单的应用程序,将人名、关系和星座作为输入并存储在本地存储中。这需要打印为 Name: text input, Relation: Selected input, Zodiac: Selected input。

HTML

<form>
    <label>Name</label>
    <input type="text" id="names">
    <label>Relationship</label>
    <select name="select1" id="relation">
<option value = "Husband">Husband</option>
<option value = "Wife">Wife</option>
<option value = "Sister">Sister</option>
<option value = "Cousin">Cousin</option>
<option value = "Friend">Friend</option>    
</select>
    <label>Zodiac</label>
    <select name="select2" id="stars">
<option value = "Aries">Aries</option>
<option value = "Taurus">Taurus</option>
<option value = "Gemini">Gemini</option>
<option value = "Cancer">Cancer</option>
<option value = "Leo">Leo</option>
<option value = "Virgo">Virgo</option>

<input type="button" value="Submit" id="btn">
<div id="logger"><pre></pre></div>
    
</form>

JS/JQuery

$(document).ready(function () {
$("#btn").click(function () {
    var myMemory = {};
myMemory.name = document.getElementById('names').value;
myMemory.relation = document.getElementById('relation').value;
myMemory.star = document.getElementById('stars').value;

//if user already has memories in local, get that array and push into it.
//else create a blank array and add the memory.
var memories = localStorage.getItem('memories') ?
              JSON.parse(localStorage.getItem('memories')) : 
              [];
memories.push(myMemory);
localStorage.setItem('memories', JSON.stringify(memories));
    }); 

dataString = localStorage.getItem('memories');
stored = JSON.parse(dataString);
logger.innerHTML = JSON.stringify(stored);
}); 

解析本地存储时得到的输出是这样的,

[{"name":"Kevin","relation":"Friend","star":"Aries"},{"name":"John","relation":"Brother","star":"Gemini"}]

我想将其格式化如下。请帮忙。

name: Kevin, relation: Friend, star: Aries
name: John, relation: Brother, star: Gemini

【问题讨论】:

  • “格式化”用什么方式?
  • 当前输出为 [{"name":"Kevin","re​​lation":"Friend","star":"Aries"},{"name":"John","re​​lation" :"Brother","star":"Gemini"}] 我想要姓名:Kevin 关系:朋友,明星:白羊座姓名:John,关系:兄弟,明星:双子座 基本上没有方括号和大括号

标签: arrays object local-storage


【解决方案1】:

试试这个代码:

var arr = [{"name":"Kevin","relation":"Friend","star":"Aries"},{"name":"John","relation":"Brother","star":"Gemini"}] // replace this variable with your "stored" variable (after JSON.parse)

var output = '';

for (var i = 0; i < arr.length; i++) {
  output += "Name: " + arr[i].name + ", Relation: " + arr[i].relation + ", Star: " + arr[i].star + "\n"
}

console.log(output)

【讨论】:

  • Devashish,非常感谢,您的及时帮助确实是我正在寻找的答案。这解决了。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-11
  • 2021-01-11
相关资源
最近更新 更多