1

I was wondering how to convert an array to an actual JSON object with keys and values. I am creating a Node.js command-line flag parser, and I would like to transform this:

[ '--input', 'HI!' ]

to this:

{ "--input": "HI!" }

as an example. JSON.stringify will not solve this problem, as JSON.stringify gives me this:

["--input","HI!"]

which is not what I want. If there is a way to solve this problem using JSON.stringify I am still open, but to my knowledge just using JSON.stringify will not solve this problem.

6
  • What would be an expected result for the array ['a', 'b', 'c']? Commented Nov 25, 2018 at 21:21
  • Does your array always have just two items? Commented Nov 25, 2018 at 21:21
  • C would be a value with a predefined key, @georg. Commented Nov 25, 2018 at 21:21
  • @MarkMeyer no it may have more Commented Nov 25, 2018 at 21:22
  • 1
    Will it always have multiples of 2 as the number of values in the array? Commented Nov 25, 2018 at 21:24

2 Answers 2

3

It seems like a simple for loop is quick and easy to read here:

let arr = [ '--input', 'HI!' , 'test'] 

let obj = {}
for (let i = 0; i < arr.length; i+=2){
  obj[arr[i]] = (arr[i+1] != undefined) ? arr[i+1] : {}
}
console.log(obj)

You could also do more-or-less the same thing with reduce():

let arr = [ '--input', 'HI!' , 'test'] 

let o = arr.reduce((obj, item, i, self) =>{
  if (i%2 == 0) 
    obj[item] = self[i+1] != undefined ? self[i+1] : {someDefault: "value"}
  
  return obj
}, {})

console.log(o)

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

3 Comments

Sure, @mikey, you would just replace the {} with your value. See edit on the second snippet.
Look at my answer -- Instead of having JSON inside of JSON, it just has it put a pre-defined key in the main JSON. Thank you for your answer- it helped me make mine!
glad it helped @Mikey.
0

Adding on to @markmeyer's answer, a for loop would be easy to read here:

let arr = [ '--input', 'HI!' , 'test'] 
let obj = {}
for (let i = 0; i < arr.length; i+=2) {
  if (arr[i+1] != undefined) {
    obj[arr[i]] = arr[i+1];
  } else {
    obj["<predefinedkey>"] = arr[i];
  }
}
console.log(obj)

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.