将对象列表转换为对象

时间:2018-05-29 01:18:22

标签: javascript

我有对象的输入列表,

[
{"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 个答案:

答案 0 :(得分:2)

使用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);




答案 1 :(得分:1)

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)