【问题标题】:Convert array of Objects to an Array [duplicate]将对象数组转换为数组[重复]
【发布时间】:2017-08-11 01:00:46
【问题描述】:

我知道以前有人问过这个问题,但我发现的每个解决方案都没有按照我需要的方式进行。

数组

[ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ]

我需要的对象

{
"Title": "Default Text", 
"Title2": "Default Text2"
}

我尝试的一切似乎都返回了这个错误:

{ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} }

我已经尝试了我在 SO 上找到的大多数东西。我尝试过的最后一个格式错误的是:

let obj = Object.assign({}, arrayHere);

我想要什么:

我不断得到的,但是是错误的:

【问题讨论】:

    标签: javascript ecmascript-6


    【解决方案1】:

    使用 Array.prototype.map(),

    var Object = [ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ];
    
    var result = Object.map(function(obj) {
                 var rObj = {};
                 rObj[obj.key] = obj.value;
                 return rObj; });
    

    【讨论】:

      【解决方案2】:

      您可以使用Array#mapObject.assign 分配单个创建的对象

      var array = [{ key: "Title", value: "Default Text" }, { key: "Title2", value: "Default Text2" }];
          object = Object.assign({}, ...array.map(o => ({ [o.key]: o.value })));
          
      console.log(object);

      【讨论】:

        【解决方案3】:
        const a = [ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ];
        
        function convertArr(arr) {
            const res = {};
        
            a.forEach((item) => 
               res[item.key] = item.value;
            })
            return res;
        }
        
        convertArr(a);
        

        【讨论】:

          【解决方案4】:

          使用Array.prototype.reduce()函数:

          var arr = [ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ],
              result = arr.reduce((r,o) => {r[o.key] = o.value; return r; }, {});
          
          console.log(result);

          【讨论】:

          • 好的,让我试试 brb
          • 谢谢你
          • @user1189352,不客气
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-19
          • 2016-03-22
          • 2019-08-06
          • 1970-01-01
          • 2019-07-14
          相关资源
          最近更新 更多