简体   繁体   English

如何将一组对象缩减为一个具有唯一属性的 object? JavaScript

[英]How to reduce an array of objects into one object with unique properties? JavaScript

How can I reduce an array of objects into one object, with unique properties.如何将一组对象缩减为一个 object,具有独特的属性。 I will appreciate any help!我将不胜感激任何帮助! Thank you!谢谢!

 const input = [ { "a": false}, { "b": false, "c": true }, { "b": false, "c": true }, { "a": false }, { "b": false, "c": true }, { "b": false, "c": true }, { "b": false, "c": true, "b": false } ] // I tried: const object = input.reduce( (obj, item) => Object.assign(obj, { [item.key]: item.value }), {}); console.log( object );
but I get: 但我得到:

{"a":false,"b":false,"c":true}

Expected result:预期结果:

 {"a":false,"b":false,"c":true}

As you can tell, by using the Array.reduce() method, we can reduce the array to an object by initializing the reducer using an empty object ({}) as the second argument of Array.reduce().如您所知,通过使用 Array.reduce() 方法,我们可以通过使用空的 object ({}) 作为 Array.reduce() 的第二个参数来初始化化简器,从而将数组缩减为 object。

And then in the reducer callback, we can work our way up to build the object using the Object.assign() method like how we initially wanted as an end result.然后在 reducer 回调中,我们可以使用 Object.assign() 方法逐步构建 object,就像我们最初想要的最终结果一样。

something like this:是这样的:

const inputObject = input.reduce(
    (previousObject, currentObject) => {
        return Object.assign(previousObject, currentObject);
    },
{});

console.log(inputObject);

 let input = [ { a: false }, { b: false, c: true }, { b: false, c: true }, { a: false }, { b: false, c: true }, { b: false, c: true }, { b: false, c: true, b: false }, ]; let result = input.reduce((prev, curr) => { Object.assign(prev, curr); return prev; }, {}); console.log(result);

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

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