I have a nested array like this:
var arr = [
['Simcard', 'one'],
['Charge', 'two'],
];
I want to make it like this:
[
{"Simcard": "one"},
{"Charge": "two"},
]
How can I do that?
Here is what I've tried but not exactly the expected result:
let res = Object.keys(x).map((key) => {key: x[key]});
CodePudding user response:
There's a builtin Object.fromEntries
that turns a two-element array into an object.
var arr = [
['Simcard', 'one'],
['Charge', 'two'],
];
var desired = [
{"Simcard": "one"},
{"Charge": "two"},
]
var answer = arr.map(entry => Object.fromEntries([entry]));
console.log(answer)
CodePudding user response:
This is not a oneliner, but you could try the following
let res = []
arr.forEach(element => res[element[0]] = element[1])
CodePudding user response:
let res = arr.map(item => ({[item[0]]: item[1]}))