将数组转换为一个对象数组

时间:2016-08-02 18:00:45

标签: javascript arrays angularjs object underscore.js

我有以下数组列表。

<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"];

任何人都可以让我知道如何实现这一目标。

4 个答案:

答案 0 :(得分:7)

使用Array.maphttps://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)

JSFIDDLE

答案 3 :(得分:1)

Underscore方式(对于没有Array.map支持的旧浏览器):

var res = _.map(data, function(p, i){
    return {id: i + 1, label: p};
});