user1938143
user1938143

Reputation: 1184

How to loop an object and push key value into a key-value object

I dont know, how to loop an object and push his key and value into a key-value object. now I give you an example.

input object looks like this:

{a: 1, b:2, c:3}

and the output object array should be look like this:

[{key: a, value: 1}{key: b, value 2} {key: c, value: 3}]

any solutions?

Upvotes: 1

Views: 2859

Answers (3)

Rajesh kumar R
Rajesh kumar R

Reputation: 214

A short method

Object.entries(obj).map(([key, value])=> ({key, value}));

Upvotes: 0

StepUp
StepUp

Reputation: 38094

It is possible to use Object.entries method:

Object.entries(obj).map(([k, v])=> ({key: k, value: v}));

An example:

let obj = {a: 1, b:2, c:3};
const result = Object.entries(obj).map(([k, v])=> ({key: k, value: v}));
console.log(result);

As mdn says:

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop.

Upvotes: 4

1pulsif
1pulsif

Reputation: 499

new Map(Object.entries({a: 1, b:2, c:3}));

Upvotes: 3

Related Questions