How to optimize this transformation from array to object with specific key?
I have this array that inside has other arrays, and I wanted to turn this array into an array of objects. I would like to do this without using this index, and the object would like it to have these specific keys. I'm new to javascript and I would like to know if the way I did it was the best way, or if I can use a Map or Reduce to do what I want.
const listaCesar = [["cesar", "1", 1], ["thiago", "2", 2], ["giuseppe", "3", 3]]
const dict = []
listaCesar.forEach(item => dict.push({name: item[0], id: item[1], age: item[2]}))
console.log(dict)
This code works and gives me the expected result, but I don't know if I did it in the best way
ExpectResult = [{name: "cesar", id: "1", age: "1"}, {name: "thiago", id: "2", age: "2"}, {name: "giuseppe", id: "3", age: "3"}]
CodePudding user response:
your solution is not bad, but I think you want something more "Elegant" so you can reduce your function to something like this:
const dict = listaCesar.map(([name, id, age]) => ({ name, id, age }));
basically with [name, id, age]
you are destructuring the inner array and using those same names in the object { name, id, age }
you will create a key value object with those name as keys.
const listaCesar = [
["cesar", "1", 1],
["thiago", "2", 2],
["giuseppe", "3", 3]
]
const dict = []
listaCesar.forEach(item => dict.push({
name: item[0],
id: item[1],
age: item[2]
}))
console.log(dict);
console.log('////////////////////////////////////////');
const dict2 = listaCesar.map(([name, id, age]) => ({
name,
id,
age
}));
console.log(dict2);
if you want something more performant
to avoid using another structure you can reuse the same array that you have following the same approach, in this case you do not return a new array instead you reuse the same index on the array to put your new object.
const listaCesar = [
["cesar", "1", 1],
["thiago", "2", 2],
["giuseppe", "3", 3]
]
listaCesar.forEach(([name, id, age], i) => {
listaCesar[i] = {
name,
id,
age
}
})
console.log(listaCesar);
CodePudding user response:
One improvement you can do is use an array to keep names of properties and loop over it to create object, so that it becomes extensible
const listaCesar = [
["cesar", "1", 1],
["thiago", "2", 2],
["giuseppe", "3", 3]
]
const props = ['name', 'id', 'age', ]
const dict = listaCesar.map(item => props.reduce((a, b, i) => {
a[b] = item[i]
return a
}, {}))
console.log(dict)