Converting An Array To An Object
Solution 1:
Your code has several issues.
The target object is reset to
{}
in each iteration. So you should movevar object = {}
out of your loop.You return from inside your loop, which immediately ends it: that should happen after the loop.
You iterate one time too few. Remove the
- 1
:for (var i = 0; i < array.length; ++i) {
There is an assignment to a numerical property, which you delete 2 lines later: that is a costly operation, which you should avoid. Just do the assignment in one operation:
object[newArray[0]] = newArray[1];
Here is everything corrected:
var array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]];
functionfromListToObject() {
var object = {}; // out of the loopfor (var i = 0; i < array.length; ++i) { // iterate to lastvar newArray = array[i];
object[newArray[0]] = newArray[1];
}
return object; // out of the loop
}
var obj = fromListToObject(array);
console.log(obj);
ES6 Version
If you can use ES6 syntax, then consider this solution:
functionfromListToObject(array) {
returnObject.assign(...array.map( ([key,val]) => ({[key]: val}),{}));
}
const array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]];
const obj = fromListToObject(array);
console.log(obj);
Using Map
You might also be interested in the ES6 Map
object, which works similarly to an object, and can be constructed from your array in the most simple way:
const mp = newMap(array);
You can then access the key values as follows:
mp.get('make') === 'Ford';
And iterate:
mp.forEach( function (val, key) {
console.log(key, val);
});
Solution 2:
Try this
You have declared obj
inside the loop.
During iteration
object = Object {make: "Ford"}, i = 0
After the first iteration your function
console.log(fromListToObject(array));
is called. This is because you call the return inside the loop, this should be done outside the loop. Rewrite your code as
var array = [
['make', 'Ford'],
['model', 'Mustang'],
['year', 1964]
],
i, j = array.length,
object = {}
functionfromListToObject() {
for (i = 0; i < j; i++) {
var newArray = array[i];
object[i] = newArray[1];
object[newArray[0]] = object[i];
delete object[i];
}
return object;
}
console.log(fromListToObject(array));
var array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]];
var obj = {};
array.forEach(function(data){
obj[data[0]] = data[1]
});
console.log(obj);
Solution 3:
While: Not Counting!
object = {};
while( array[0] )object[ array[0][0] ] = array[0][1], array.shift();
will result in:
object;
>> Object { make: "Ford", model: "Mustang", year: 1964 }
array;
>> Array [ ]
This action will actually dispatch array members for patching the object! The array content will be physically dislocated to the newly declared object.
Post a Comment for "Converting An Array To An Object"