I have an array.
var nestedArr =[['loop0', 0], ['loop1', 1], ['loop2', 2], ['loop3', 3], ['loop4', 4], ['loop5', 5]]
I have to get using for loop this:
var obj = { loop0: 0, loop1: 1, loop2: 2 ...};
I am trying this :
for(var j = 0; j < nestedArr.length; j++){
obj[nestedArr[j][0]] = nestedArr[j][1]}
but I am getting values as undefined. How do I add values correctly.
3 Answers 3
Working fine for me. Just added the definition of obj
var nestedArr =[['loop0', 0], ['loop1', 1], ['loop2', 2], ['loop3', 3], ['loop4', 4], ['loop5', 5]],
obj = {};
for(var j = 0; j < nestedArr.length; j++){
obj[nestedArr[j][0]] = nestedArr[j][1]
}
console.log(obj)
answered May 28, 2018 at 8:00
Muhammad Usman
10.1k26 silver badges41 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Nina Scholz
it does not explain why but I am getting values as undefined.
Muhammad Usman
because it is not giving you undefined
You can use reduce function as below:
var nestedArr = [
['loop0', 0],
['loop1', 1],
['loop2', 2],
['loop3', 3],
['loop4', 4],
['loop5', 5]
];
var output = {};
nestedArr.reduce(function(itm) {
output[itm[0]] = itm[1];
});
console.log(output);
Your loop also is correct:
var nestedArr = [
['loop0', 0],
['loop1', 1],
['loop2', 2],
['loop3', 3],
['loop4', 4],
['loop5', 5]
];
var obj = {};
for (var j = 0; j < nestedArr.length; j++) {
obj[nestedArr[j][0]] = nestedArr[j][1]
}
console.log(obj)
answered May 28, 2018 at 7:58
Saeed
5,4983 gold badges31 silver badges43 bronze badges
5 Comments
CertainPerformance
I wasn't the downvoter, but
.map is not appropriate when you aren't returning anything - use .reduce insteadNina Scholz
map ... without using the result. btw the given code of op works.
Saeed
I change it to
reduceCertainPerformance
@Satpal Why
forEach? If reducing an array into an object, that's exactly what reduce is forSaeed
Your for loop is correct and you see it runs well. whats the problem? @blahblahvah
Using Array.prototype.reduce you can do this.
var nestedArr =[['loop0', 0], ['loop1', 1], ['loop2', 2], ['loop3', 3], ['loop4', 4], ['loop5', 5]]
const res = nestedArr.reduce((acc, v) => {
acc[v[0]] = v[1];
return acc;
}, {});
console.log(res);
answered May 28, 2018 at 8:03
Matus Dubrava
14.6k3 gold badges44 silver badges60 bronze badges
Comments
lang-js
var obj = {}, the code works.