让我说我有一个像这样的数组:
[ { full_name: 'Sickö' },
{ location: 'New York City, United States' },
{ follower: '1.2M' },
{ er: '5.59%' },
{ topics: 'Fashion' } ]
我想将其作为一个对象,例如:
{
fullname: 'Sicko',
location: 'New York City, United State'
..and more
}
我知道我可以使用Object.assign
组合它们,但不知道如何分配所有它们。
答案 0 :(得分:4)
let all = [ { full_name: 'Sickö' },
{ location: 'New York City, United States' },
{ follower: '1.2M' },
{ er: '5.59%' },
{ topics: 'Fashion' } ];
let res = Object.assign({}, ...all);
答案 1 :(得分:1)
您可以使用Array.reduce()并从等于空对象{}
的累加器开始,并在化简器的每次迭代中使用Object.assign()。像这样:
const input = [
{full_name: 'Sickö'},
{location: 'New York City, United States'},
{follower: '1.2M'},
{er: '5.59%'},
{topics: 'Fashion'}
];
function assign(acc, obj)
{
return Object.assign(acc, obj);
}
let res = input.reduce(assign, {});
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
但是,Object.assign()
旨在接受多个sources
,因此,如果您有ES6
支持,则可以将其与spread syntax一起使用:
const input = [
{full_name: 'Sickö'},
{location: 'New York City, United States'},
{follower: '1.2M'},
{er: '5.59%'},
{topics: 'Fashion'}
];
let res = Object.assign({}, ...input);
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
答案 2 :(得分:0)
在标记jquery时,以防您需要使用相同的解决方案:
var data = [ { full_name: 'Sickö' },
{ location: 'New York City, United States' },
{ follower: '1.2M' },
{ er: '5.59%' },
{ topics: 'Fashion' } ];
var d = $.extend({}, ...data);
console.log(d);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>