Mikey
Mikey

Reputation: 314

Convert array to JSON using keys and values

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.

Upvotes: 1

Views: 1249

Answers (2)

Mikey
Mikey

Reputation: 314

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)

Upvotes: 0

Mark
Mark

Reputation: 92440

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)

Upvotes: 3

Related Questions