简体   繁体   English

JavaScript 将对象数组减少到 object 字典

[英]JavaScript Reduce Array of objects to object dictionary

I've read this answer on SO to try and understand where I'm going wrong, but not quite getting there.我已经在 SO 上阅读了这个答案,试图了解我哪里出错了,但还没有完全到达那里。

I have this function:我有这个 function:

get() {
    var result = {};

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

    return result;
}

It turns this:它变成了这样:

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

To this:对此:

{ Some: "20160608" }

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.我想,这正是reduce的用途,我有一个数组,我想在它的末尾有一个值。

So I thought this:所以我想到了这个:

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

But that doesn't produce the correct result.但这不会产生正确的结果。

1) Can I use Reduce here? 1) 我可以在这里使用 Reduce 吗?

2) Why does it not produce the correct result. 2)为什么它不产生正确的结果。

From my understanding, the first iteration the result would be an empty object of some description, but it is the array itself.据我了解,第一次迭代的结果将是一些描述的空 object,但它是数组本身。

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!那么,您将如何在第一次迭代中重新定义它 - 这些想法让人感觉在这种情况下它是不正确的!

Set initial value as object将初始值设置为对象

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

Since 2019 (ES2019) you can go with Object.fromEntries() but you need to map to array first.自 2019 年(ES2019)以来,您可以使用 go 和Object.fromEntries()但您需要先进行 map 阵列。

const filtersObject = Object.fromEntries(filters.map(({ name, value }) => [name, value])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM