0

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.

1
  • why are you pushing array objects into a single object? Commented Apr 16, 2017 at 21:13

2 Answers 2

3

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.

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

2 Comments

In ES6 you can just do Object.assign({}, ...input).
You are correct. I started with [{}].concat(input) and moved to [{}, ...input], but that one is better
2

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;
}, {});

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.