EN
JavaScript - how can I convert array of strings to array of objects?
1
answers
6
points
I have this specific problem.
// I have:
var array = ['x', 'y'];
// I need to convert above array to below object.
// Frist object needs to have 2 properties 'a' and 'b' with same value from array[0]
// Second object needs to have 2 properties 'a' and 'b' with same value from array[1]
// result:
var objects = [
{
'a': 'x',
'b': 'x'
},
{
'a': 'y',
'b': 'y'
}
];
I know how to convert it with simple for loop.
How to do this in the better way?
1 answer
5
points
Quick solution using map function:
// ONLINE-RUNNER:browser;
var array = ['x', 'y'];
var objects = array.map(value => (
{
'a': value,
'b': value
}
));
console.log(JSON.stringify(objects)); // [{"a":"x","b":"x"},{"a":"y","b":"y"}]
Solution using forEach:
// ONLINE-RUNNER:browser;
var array = ['x', 'y'];
var objects = [];
array.forEach(value => objects.push({ 'a': value, 'b': value }));
console.log(JSON.stringify(objects)); // [{"a":"x","b":"x"},{"a":"y","b":"y"}]
Implementation you mentioned in your question, using simple for:
// ONLINE-RUNNER:browser;
var array = ['x', 'y'];
var objects = [];
for (var i = 0; i < array.length; i++) {
objects.push({ 'a': array[i], 'b': array[i] });
}
console.log(JSON.stringify(objects)); // [{"a":"x","b":"x"},{"a":"y","b":"y"}]
1 comments
Add comment
I prefer the map solution by far or the for ... of method so you can directly access the values of the array.
for (let val of array) {
objects.push({ 'a': val, 'b': val });
}
Another possibility is to use the Object.fromEntries() method but for nested or multidimensional objects that becomes more a haste than a joi.