method input: (['name', 'marcus'], ['address', 'New York']
method output: {name: marcus, address: New York}
How do i do it?
cont array = [['c','2'],['d','4']];
function objectify()
{
array.forEach(arrayElement => { for(let i = 0; i<2; i++){
const obj = Object.assign({array[i][i]}, array[i++])
}
return obj;
})
}
console.log(objectify);
You can use Object.fromEntries()
const data = [['name', 'marcus'], ['address', 'New York']];
const result = Object.fromEntries(data);
console.log(result);
1) If you are using forEach then you don't have to use for loop inside it
array.forEach(arrayElement => { for(let i = 0; i<2; i++){
const obj = Object.assign({array[i][i]}, array[i++])
}
2) You shouldn't hardcode the length upto which i will run, because it can be of any length.
for(let i = 0; i<2; i++)
If you are using forEach then you should loop over the array and get the key and value and set it into the resultant object.
function objectify(array) {
const result = {};
array.forEach((o) => {
const [key, value] = o;
result[key] = value;
});
return result;
}
const array = [
["c", "2"],
["d", "4"],
];
console.log(objectify(array));