1

I have some code that outputs an object with key value pairs. Like so:

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

I would like to change that output to this instead:

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

I have fiddled around with Object.entries(), Object.assign() and Array.map() without getting much further. I have put so much time into this now so I figured it was time to ask for some help.

The initial data is from req.query which I have then managed to convert from:

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

into

{"x.a": "1", "x.b": "2", "x.c": "3"}

This will eventually become a mongoDB query.

Below is what I have so far.

let obj = Object.entries(req.query);
obj = obj.map(([key, val]) => ["x."+ key, val]);
let newobj = Object.assign(...obj.map(([k, v]) => ({ [k]: v })));

which gives:

{"x.a": "1", "x.b": "2", "x.c": "3"}

so, as per my initial question. How do I turn this into:

[{"x.a" : "1"}, {"x.b" : "2"}, {"x.c" : "3"}]
1
  • i know this code is not pretty and there is likely a number of ways to shorten this down... Commented Sep 2, 2019 at 11:18

1 Answer 1

2

You can use Object.entries and map

let obj = {
  "a": "1",
  "b": "2",
  "c": "3"
}

let final = Object.entries(obj).map(([k, v]) => ({
  [`x.${k}`]: v
}))

console.log(final)

If you just want key instead of x.a, you can use simply use

 [k] : v 
Sign up to request clarification or add additional context in comments.

6 Comments

No dupe available at all?
@mplungjan sorry not so good at finding them, if you found something you have my vote also there
Add mongo and they will even be closer
@mplungjan okay thanks :) what this line means Add mongo and they will even be closer ?
This will eventually become a mongoDB query. so I added mongo to the search and found more conversions from array to mongoDB arrays
|

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.