【问题标题】:Create an Array of Object from an Array of Strings with Lodash使用 Lodash 从字符串数组创建对象数组
【发布时间】:2015-07-28 14:04:41
【问题描述】:

我有以下数组;

["Test1", "Test2", "Test3"]

我希望它是这样的;

[{ id: 0, name: "Test1" }, { id: 1, name: "Test2" }, { id: 2, name: "Test3" }]

有什么帮助吗? 我想我应该以某种方式使用_.object() 来完成这个任务。

【问题讨论】:

    标签: arrays angularjs object lodash


    【解决方案1】:

    map() 函数是你的朋友:

    _.map(array, function(item, index) {
        return { id: index, name: item };
    });
    

    【讨论】:

      【解决方案2】:

      当您使用 Angular 时,这应该可以解决问题。

      var newArray = [];
      angular.forEach(myArray,function(item, key){
          newArray.push({id:key, name:item});
      });
      

      【讨论】:

        【解决方案3】:

        以下解决方案不需要角度,仅基于lodash:

        var newArray = [];
        
        _.forEach(["Test1", "Test2", "Test3"], function (item, key) {
            newArray.push({
                id: key,
                name: item
            });
        });
        

        【讨论】:

          猜你喜欢
          • 2019-07-30
          • 1970-01-01
          • 1970-01-01
          • 2018-05-13
          • 1970-01-01
          • 1970-01-01
          • 2018-01-22
          • 2019-03-20
          • 2016-10-18
          相关资源
          最近更新 更多