代码之家  ›  专栏  ›  技术社区  ›  tree em

将对象列表转换为对象

  •  -1
  • tree em  · 技术社区  · 6 年前

    我有对象的输入列表,

    [
    {"id":1,"name":"USD - US Dollar","country":"US","created_at":"2018-05-28 
    14:54:24","updated_at":"2018-05-28 14:54:24"},
    {"id":2,"name":"TH- Thai Bat","country":"TH","created_at":"2018-05-28 
    14:54:24","updated_at":"2018-05-28 14:54:24"}
    ] 
    

    我想变成,任何人请引导我。

    {"US": "USD - US Dollar","TH": "TH- Thai Bat"}
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   CertainPerformance    6 年前

    使用 reduce 要将数组转换为单个对象:

    const input = [
    {"id":1,"name":"USD - US Dollar","country":"US","created_at":"2018-05-28 14:54:24","updated_at":"2018-05-28 14:54:24"},
    {"id":2,"name":"TH- Thai Bat","country":"TH","created_at":"2018-05-28 14:54:24","updated_at":"2018-05-28 14:54:24"}
    ];
    
    const output = input.reduce((a, { name, country }) => {
      a[country] = name;
      return a;
    }, {});
    console.log(output);
        2
  •  1
  •   jspcal    6 年前

    除了 reduce 您还可以:

    arr = [
        {"id":1,"name":"USD - US Dollar","country":"US","created_at":"2018-05-28 14:54:24","updated_at":"2018-05-28 14:54:24"},
        {"id":2,"name":"TH- Thai Bat","country":"TH","created_at":"2018-05-28 14:54:24","updated_at":"2018-05-28 14:54:24"}
    ]
    
    obj = {}
    
    arr.forEach(function(el) {
        obj[el.country] = el.name
    })
    
    console.log(obj)