0

I am learning javascript.

I am recieving a variable length of dictionary from the command line of the form

--myargs = {"foo":"bar", "foo2":"bar2"}

I can read the args by

var argv = require('minimist')(process.argv.slice(2));
console.dir(argv)
var myargs = argv["myargs"] 

I need to unpack the dictionary myargs like this->

my_new_args= {Key: "foo", Value: "bar", Key: "foo2", Value: "bar2" }; 

How do I do this in JS?

Pavlo
  • 43,301
  • 14
  • 77
  • 113
Illusionist
  • 5,204
  • 11
  • 46
  • 76

1 Answers1

2

You can use map() on object keys and return array of objects.

var myargs = {"foo":"bar", "foo2":"bar2"}
var result = Object.keys(myargs).map(e => ({Key: e, Value: myargs[e]}));
console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • 1
    You're welcome, note that you cant have same keys in object – Nenad Vracar May 05 '17 at 15:34
  • 1
    Yeah, that confused me, the result he wants in `my_new_args` is actually illegal Javascript. Fair play for figuring out what OP probably really wanted. – Karl Reid May 05 '17 at 15:38
  • I actually have another bug in my code, `var argv = require('minimist')(process.argv.slice(2)); console.dir(argv) var myargs = argv["myargs"] ` is not returning `{"foo":"bar", "foo2":"bar2"}` but its returning `{` – Illusionist May 05 '17 at 15:38
  • @Illusionist What is it returning then? – Nenad Vracar May 05 '17 at 15:42
  • Its returning just `{` , I am trying to pass `--tags={"foo":"bar", "foo2":"bar2"}` . I tried escape charactesr and wrapping the dict in quotes – Illusionist May 05 '17 at 15:45
  • I never used that package but i think your input should look like this `node yourFile.js -foo bar -foo2 bar2` – Nenad Vracar May 05 '17 at 15:51