admin管理员组文章数量:1333414
How can I reduce an array of objects into one object, with unique properties. 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 );
How can I reduce an array of objects into one object, with unique properties. 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:
{ "undefined": undefined }
Expected result:
{"a":false,"b":false,"c":true}
Share
Improve this question
edited Nov 18, 2022 at 19:17
Camilo
7,2145 gold badges45 silver badges66 bronze badges
asked Nov 18, 2022 at 15:58
ryy77ryy77
1,2947 gold badges23 silver badges43 bronze badges
6
- What do you mean by unique properties? – mrconcerned Commented Nov 18, 2022 at 15:59
- What have you tried so far? – Camilo Commented Nov 18, 2022 at 16:00
-
You can use
input.reduce()
with proper callback function. You can useObject.assign()
as a part of it. – Roman Hocke Commented Nov 18, 2022 at 16:03 - @Nijat Mursali, i mean "a", "b", "c" to be only once – ryy77 Commented Nov 18, 2022 at 16:09
- stackoverflow./help/formatting – Mister Jojo Commented Nov 18, 2022 at 16:10
2 Answers
Reset to default 2
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);
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().
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.
something like this:
const inputObject = input.reduce(
(previousObject, currentObject) => {
return Object.assign(previousObject, currentObject);
},
{});
console.log(inputObject);
本文标签: How to reduce an array of objects into one object with unique properties JavaScriptStack Overflow
版权声明:本文标题:How to reduce an array of objects into one object with unique properties? JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742332091a2454896.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论