Let's say you have an array like this:
let y = [{"a": { "id": 1 } }, { "b": { "id": 2 } }, { "c": { "id": 3 } }];
You can see that this is a very inefficient way to store data. It would be so much better to have these three distinct JSON objects as properties of a single JSON object like this:
{ "a": { "id": 1 }, "b": { "id": 2 }, "c": { "id": 3 } }
How can we achieve this?
Enter Object.assign
:
y = Object.assign(...y, {});
// y == { "a": { "id": 1 }, "b": { "id": 2 }, "c": { "id": 3 } }
See that neat little thing I did with the spread (...
) operator? That's where the magic happens. This kind of conversion of an array into a JSON object can come handy in another situation as well. Let me show you.
Let's say you have another JSON object like this:
let x = { "d": { "id": 4 }, "e": { "id": 5 } };
And you want to prepend the values of the array y
to this object, because you'd like to have your keys in alphabetical order (or some other practical reason). You can use Object.assign
for that:
x = Object.assign(...y, x);
// x == { "a": { "id": 1 }, "b": { "id": 2 }, "c": { "id": 3 }, "d": { "id": 4 }, "e": { "id": 5 } }
Isn't that neat? So this is how you can use Object.assign
to:
- Convert an array of JSON objects into a single JSON object
- Prepend a JSON object with properties from another JSON object
Well, I hope this trick comes handy to you one day. Happy coding!