JavaScript将对象数组减少到对象字典 [英] JavaScript Reduce Array of objects to object dictionary

查看:89
本文介绍了JavaScript将对象数组减少到对象字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在SO上阅读了这个答案,试着去了解哪里我错了,但还没到那儿。

I've read this answer on SO to try and understand where I'm going wrong, but not quite getting there.

我有这个功能:

get() {
    var result = {};

    this.filters.forEach(filter => result[filter.name] = filter.value);

    return result;
}

它转为:

[
    { name: "Some", value: "20160608" }
]

对此:

{ Some: "20160608" }

我想,这正是 reduce 是因为,我有一个数组,我想在它的末尾有一个单值。

And I thought, that is exactly what reduce is for, I have an array, and I want one single value at the end of it.

所以我想这个:

this.filters.reduce((result, filter) => {
    result[filter.name] = filter.value;
    return result;
});

但这不会产生正确的结果。

But that doesn't produce the correct result.


1)我可以在这里使用Reduce吗?

1) Can I use Reduce here?

2)为什么它不会产生正确的结果。

2) Why does it not produce the correct result.

根据我的理解,第一次迭代结果将是某个描述的空对象,但它是数组本身。

From my understanding, the first iteration the result would be an empty object of some description, but it is the array itself.

那么你将如何在第一次迭代中重新定义 - 这些想法激起了在这种情况下不正确的感觉!

So how would you go about redefining that on the first iteration - these thoughts provoke the feeling that it isn't right in this situation!

推荐答案

将初始值设置为对象

this.filters = this.filters.reduce((result, filter) => {
    result[filter.name] = filter.value;
    return result;
},{});
//-^----------- here

var filters = [{
  name: "Some",
  value: "20160608"
}];

filters = filters.reduce((result, filter) => {
  result[filter.name] = filter.value;
  return result;
}, {});

console.log(filters);

var filters = [{
  name: "Some",
  value: "20160608"
}];

filters = filters.reduce((result, {name, value}= filter) => (result[name] = value, result), {});

console.log(filters);

这篇关于JavaScript将对象数组减少到对象字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆