'How to make the nested items of array to object?
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]});
Solution 1:[1]
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)
Solution 2:[2]
This is not a oneliner, but you could try the following
let res = []
arr.forEach(element => res[element[0]] = element[1])
Solution 3:[3]
let res = arr.map(item => ({[item[0]]: item[1]}))
Solution 4:[4]
You can use Array#map as follows. I think you biggest challenge was having the key in a variable: so that the word key does not become the key but it's value we use [key] instead.
const arr = [ ['Simcard', 'one'], ['Charge', 'two'] ],
res = arr.map(([key,value]) => ({[key]: value}));
console.log( res );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | RickyP |
| Solution 4 | PeterKA |
