我有以下数组列表。
<body class="serviceBody" id="bodyColour">
<div class="wrapper">
<nav>
<ul>
<li><a href="#">Home</a>
</li>
<li><a id="active" href="#">Link</a>
</li>
<li><a href="#">Link</a>
</li>
<li><a href="#">Link</a>
</li>
</ul>
</nav>
<div class="servicesContent">
<div class="upperService">
<h1 class="servicesH1">Services</h1>
<h2>What we do</h2>
<p>gap gap gap gap gap gap gap gap gap gap gap gapgap gapgap gap gap gap gap gap gapgap gap gap gap gap gap gap gap gap gap gap gap gap gap gap gap gap gap gap gap gap gap gap gap gap gapgapgapgapgap gap gap gap gap gap gap gap gap gap gap gap.
<br>gap gap vvikfapfkakfapdofksapdokaspokdsapdkpokdasokdpaskdpoaskfpajf jf afj afjpaf jpoopasj f.
<br>jhadjk djkh dkjhshd kjsah dkjsah dkjash dkjah dksajhd kjashfkahf kashf kasjfh kjasfh kjasfh kajsfh akf hkajsfhksaf hkasf hkasf haskf hn</p>
<p>List:</p>
</div>
<div class="contentLists">
</div>
我需要以这种形式转换它
var data = [ "USA", "Denmark", "London"];
任何人都可以让我知道如何实现这一目标。
答案 0 :(得分:7)
使用Array.map
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
var formatted = data.map(function(country, index) {
return { id: (index + 1), label: country }
});
答案 1 :(得分:1)
简单版本:
var convertedData = []
for (var i in data){
convertedData.push({id: i+1, label: data[i]});
}
data = convertedData; //if you want to overwrite data variable
答案 2 :(得分:1)
您可以使用forEach
循环数据数组
var data = [ "USA", "Denmark", "London"];
var demArray =[];
data.forEach(function(item,index){
demArray.push({
id:index+1,
label:item
})
})
console.log(demArray)
答案 3 :(得分:1)
Underscore
方式(对于没有Array.map
支持的旧浏览器):
var res = _.map(data, function(p, i){
return {id: i + 1, label: p};
});