DEV Community

nextstep
nextstep

Posted on

Convert JS associate array to JSON

An associative array is an array with string keys rather than numeric keys[1]. Sometimes, we need to convert the array into a JSON object. Here is a single line of code to do it;

let jsArray = []
jsArray['name'] = 'foo'
jsArray['birthday'] =  '04-04-2011'

console.log(jsArray['name'])

if (Object.keys(jsArray).length !== 0) {       
   let json = Object.assign({}, jsArray)
   console.log(json)
}
Enter fullscreen mode Exit fullscreen mode

output:

foo
{
name:"foo",
birthday:"04-04-2011"
}
Enter fullscreen mode Exit fullscreen mode

https://playcode.io/776216/

Readings:

Top comments (0)