我有对象的输入列表,
[
{"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"}
答案 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)