如何将数据属性值转换为对象数组

时间:2019-01-28 09:10:19

标签: javascript jquery arrays object casting

我在data属性中具有对象数组,我想将该值作为js中的对象数组获取。我很困惑如何在js中将字符串解析为数组。这是我的数据属性:

var values = [{title:"My Office",loc:{lat:27.7081018,lng:85.3342199}},{title:"My Hostel",loc:{lat:27.7072867,lng:85.3253844}},{title:"Sudhir House",loc:{lat:27.6802258,lng:85.3805697}},{title:"Indra Chowk",loc:{lat:27.7057217,lng:85.3084168}},{title:"Jamal",loc:{lat:27.7017848,lng:85.3127387}},{title:"Patan",loc:{lat:27.5978047,lng:85.355257}},{title:"Baktapur",loc:{lat:27.6773968,lng:85.406957}},{title:"Dhulikhel",loc:{lat:27.6241873,lng:85.5410204}},{title:"Nagarjun",loc:{lat:27.7249402,lng:85.3591267}},{title:"Chitlang",loc:{lat:27.6478865,lng:85.1335696}},{title:"Pilot baba ji",loc:{lat:27.6406024,lng:85.4202461}}];

// Result I want to get
console.log(values)

// Return string
console.log($('div').attr("data-values"));

// Return single array
console.log(new Array($('div').attr("data-values")));

// Return error
console.log(JSON.parse($('div').attr("data-values")));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-values='[{title:"My Office",loc:{lat:27.7081018,lng:85.3342199}},{title:"My Hostel",loc:{lat:27.7072867,lng:85.3253844}},{title:"Sudhir House",loc:{lat:27.6802258,lng:85.3805697}},{title:"Indra Chowk",loc:{lat:27.7057217,lng:85.3084168}},{title:"Jamal",loc:{lat:27.7017848,lng:85.3127387}},{title:"Patan",loc:{lat:27.5978047,lng:85.355257}},{title:"Baktapur",loc:{lat:27.6773968,lng:85.406957}},{title:"Dhulikhel",loc:{lat:27.6241873,lng:85.5410204}},{title:"Nagarjun",loc:{lat:27.7249402,lng:85.3591267}},{title:"Chitlang",loc:{lat:27.6478865,lng:85.1335696}},{title:"Pilot baba ji",loc:{lat:27.6406024,lng:85.4202461}}]'>
</div>

在上面的代码中,我已将数组存储到data-values,并且在获取data-values的值时得到了字符串。如何将字符串解析回对象数组。

1 个答案:

答案 0 :(得分:1)

这是因为JSON格式无效,因此密钥应使用双引号引起来。

[{"title":"My Office","loc":{"lat":27.7081018,"lng":85.3342199}}]

注意:对于临时解决方法,eval()可以正常工作