0

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.

3 Answers 3

3

you could do with Array#reduce.

const details = [ { "name": "firstName", "content": "Tom" }, { "name": "lastName", "content": "Smith" }, { "name": "email", "content": "[email protected]" } ];

const res = details.reduce(
    (acc, {name, content: value}) => (acc[name] = {value}, acc), {}
);

console.log(res)

Sign up to request clarification or add additional context in comments.

2 Comments

I am using the above code in Angular 11 app. I am getting errors 1) Parameter 'acc' implicitly has an 'any' type. 2) Binding element 'name' implicitly has an 'any' type. 3) Binding element 'value' implicitly has an 'any' type.
sorry i don't know angular and type. please updated your question with angular tag. for ref please check stackoverflow.com/questions/14087489/…
2

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)

MDN Reference - Deconstructuring Assignment

Comments

2

Map the array to an array of [name, { value }] pairs, and convert to an object using Object.fromEntries().

With Typescript you'll need to set the target as ES2019 at least in your TS config, and it doesn't require any type definition (TS Playground).

const details = [{"name":"firstName","content":"Tom"},{"name":"lastName","content":"Smith"},{"name":"email","content":"[email protected]"}]

const result = Object.fromEntries(
  details.map(({ name, content: value }) => [name, { value }])
)

console.log(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.