Issue
I am having an Angular 11 app in which I have an array of objects as shown below.
details = [
{
"name": "firstName",
"content": "Tom"
},
{
"name": "lastName",
"content": "Smith"
},
{
"name": "email",
"content": "[email protected]"
}
]
I want to create an object from above array as shown below.
output = {
firstName: {value: "Tom"},
lastName: {value: "Smith"},
email: {value: "[email protected]"}
}
For simplicity I have only shown 3 objects in the details array but there can be any number of them. So I want the conversion to happen irrespective of the number of objects in the details array. How can I create the above output object? Please help me out.
Solution
Not that I’m against to the other answers proposed. As an alternative you can also do it with the help of a "for-of" loop and applying destructured assignment.
const details = [ { "name": "firstName", "content": "Tom" }, { "name": "lastName", "content": "Smith" }, { "name": "email", "content": "[email protected]" } ];
let result = {}
for ({ name: n, content: value } of details) { result[n] = { value: value }; }
console.log(result)