0

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.

2
  • Can you provide a code snippet on jsFiddle or something similar? I dont really understand your problem. Commented May 28, 2018 at 7:57
  • with a declared and initialized var obj = {}, the code works. Commented May 28, 2018 at 7:59

3 Answers 3

1

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)

2
  • it does not explain why but I am getting values as undefined. Commented May 28, 2018 at 8:02
  • because it is not giving you undefined Commented May 28, 2018 at 8:03
1

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)

5
  • 1
    I wasn't the downvoter, but .map is not appropriate when you aren't returning anything - use .reduce instead Commented May 28, 2018 at 8:00
  • 1
    map ... without using the result. btw the given code of op works. Commented May 28, 2018 at 8:00
  • I change it to reduce
    – Saeed
    Commented May 28, 2018 at 8:01
  • 1
    @Satpal Why forEach? If reducing an array into an object, that's exactly what reduce is for Commented May 28, 2018 at 8:01
  • Your for loop is correct and you see it runs well. whats the problem? @blahblahvah
    – Saeed
    Commented May 28, 2018 at 8:03
0

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.