Jiří Rejman
Jiří Rejman

Reputation: 105

Typescript - generate TS object from array

My problem is that i get an information from server - array of objects. And i would like to "push" every object from array to new object so the inupt looks:

[{key : value}],[{key2:value2}]....

And the output should look like:

{key:value,
 key2: value2 ... }

I don't know the syntax of "push" to make new object look like my desire output.

Upvotes: 0

Views: 2063

Answers (2)

Madara's Ghost
Madara's Ghost

Reputation: 174957

Here's a fun little trick:

const input = [{key: 'value'}, {key2: 'value2'}];
// Object.assign() always returns any with rest arguments, 
// you should cast to the actual type you're expecting here. 
const result = Object.assign({}, ...input) as MyApiType;

console.log(result);

How does this work?

Object.assign() will take an arbitrary number of arguments, and merges them.

Object.assign({}, {hello: 'world'}, {goodbye: 'world'}); 
// {hello: 'world', goodbye: 'world'}

We pass an empty object as the first parameter and spread input into the rest of the parameters.

Why the {}, ...input? Why not just ...input?

Because Object.assign() is destructive, it mutates the first argument passed to it. If I were to call Object.assign(...input), input[0] would have been changed. We want to avoid changing the input, because it's usually unexpected behavior to those looking at the code from the outside.

Upvotes: 3

toskv
toskv

Reputation: 31600

What you are looking for is not push put Array.reduce (plain old js). It allows you to reduce the array to a single object. You can use it this way.

let data: [{ key: string, value: string }] = [{
    key: '1',
    value: '2'
}];

let obj = data.reduce((prev, current) => {
    prev[current.key] = current.value;
    return prev;
}, {});

Upvotes: 2

Related Questions