json数组到javascript数组并将其抛给自动完成

时间:2015-06-18 07:22:49

标签: javascript jquery arrays json

我有一个像这样的JSON数组作为服务器响应返回

[{"label":"Casa Grande Trinity","idx":"14710"},{"label":"Ceebros Venkatadri","idx":"14711"},{"label":"Devinarayan Sai Saga","idx":"14712"},{"label":"Estancia","idx":"14713"},{"label":"gujarat properties","idx":"14714"},{"label":"Hi Teckno Shravan","idx":"14715"},{"label":"IPDEV","idx":"14716"},{"label":"Nahar Mangalam","idx":"14718"},{"label":"Offer Image","idx":"14719"},{"label":"Pushkar s gosel gard","idx":"14721"},{"label":"Pushkars Grace","idx":"14722"},{"label":"Rams Anjali Atrium","idx":"14723"},{"label":"Sai sagar adyar","idx":"14724"},{"label":"Utopia","idx":"14730"},{"label":"VJS The Monarch","idx":"14731"}]

所以我想将它转换为具有相同结构的JavaScript数组

我希望在自动完成中使用结果数组。

3 个答案:

答案 0 :(得分:0)

我猜你想要一个字符串数组,字符串将是每个对象的标签项目。如果是这样,您可以使用map的强大功能:

var autoComplete = response.map(function(record) {
 return record.label;
});

响应与示例数组相对应。但是,它完全取决于您使用的自动完成实现所期望的格式。如果它只是想要一组潜在的自动完成字符串,那么autoComplete将起作用。

MDN:Array.prototype.map

答案 1 :(得分:0)

你可以试试这个:

    $(function() {
    var data=[{"label":"Casa Grande Trinity","idx":"14710"},{"label":"Ceebros Venkatadri","idx":"14711"},{"label":"Devinarayan Sai Saga","idx":"14712"},{"label":"Estancia","idx":"14713"},{"label":"gujarat properties","idx":"14714"},{"label":"Hi Teckno Shravan","idx":"14715"},{"label":"IPDEV","idx":"14716"},{"label":"Nahar Mangalam","idx":"14718"},{"label":"Offer Image","idx":"14719"},{"label":"Pushkar s gosel gard","idx":"14721"},{"label":"Pushkars Grace","idx":"14722"},{"label":"Rams Anjali Atrium","idx":"14723"},{"label":"Sai sagar adyar","idx":"14724"},{"label":"Utopia","idx":"14730"},{"label":"VJS The Monarch","idx":"14731"}];

    $( "#tags" ).autocomplete({
      source: data
    });
  });

HTML:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>

演示:http://jsfiddle.net/vikashvverma/d91ze81j/

答案 2 :(得分:0)

var jsonData = JSON.parse(msg);
    for (var i = 0; i < jsonData.length; i++) {
                    x[i]=jsonData[i];
                   }
console.log(x);

这解决了我的问题