I need to convert this:
prev = {in_progress: 1, todo: 3, done: 1}
Into this
output = {[ ['Status', 'Count'], ['Todo', 3], ['In Progress', 1], ['Done', 1] ]}
When I'm trying to assign prev
to a variable, it gets assigned.
let a = {in_progress: 1, todo: 3, done: 1}
Success.
But when im trying to assign output
to a variable, it throws an error
let a = {[ ['Status', 'Count'], ['Todo', 1], ['In Progress', 2], ['Done', 3] ]}
Error:
Uncaught SyntaxError: Unexpected token ,
Can you explain the reason behind this?
The problem is that {[ ['Status', 'Count'], ['Todo', 3], ['In Progress', 1], ['Done', 1] ]}
is not a valid object literal. It's just curly braces around a list of lists. Object literals have to have key: value pairs.
If you wanted to turn it into an object, it would look like { 'Status': 'Count', 'Todo': 3, 'In Progress': 1, 'Done': 1 }
.
If you already have the list of lists and want to turn it into an object programmatically, you can do that with reduce
:
// Note: no braces
let kvlist = [ ['Status', 'Count'], ['Todo', 3], ['In Progress', 1], ['Done', 1] ];
let obj = kvlist.reduce((h,[k,v]) => { h[k] = v; return h },{});
You could get the entries and map the formatted key with the value.
const format = s => s.split('_').map(([c, ...s]) => [c.toUpperCase(), ...s].join('')).join(' '); var prev = { in_progress: 1, todo: 3, done: 1 }, result = [ ['Status', 'Count'], ...Object.entries(prev).map(([k, v]) => [format(k), v]) ]; console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.