Languages

JavaScript - how can I convert array of strings to array of objects?

6 points
Asked by:
Marcin
18610

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
Answered by:
Marcin
18610

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
Bojoer
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({ &#39;a&#39;: val, &#39;b&#39;: val }); } Another possibility is to use the Object.fromEntries() method but for nested or multidimensional objects that becomes more a haste than a joi.
Add comment
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join