最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin7PV0评论

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?

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?

Share Improve this question edited Mar 17, 2020 at 12:46 StepUp 38.3k16 gold badges92 silver badges157 bronze badges asked Mar 17, 2020 at 11:28 user1938143user1938143 1,1844 gold badges28 silver badges53 bronze badges 1
  • 2 There's a built-in function for that, it's called Object.entries – bugs Commented Mar 17, 2020 at 11:30
Add a ment  | 

3 Answers 3

Reset to default 4

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.

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

A short method

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

comment list (0)

  1. No comments so far