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)

Sign up to request clarification or add additional context in comments.

2 Comments

it does not explain why but I am getting values as undefined.
because it is not giving you undefined
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 Comments

I wasn't the downvoter, but .map is not appropriate when you aren't returning anything - use .reduce instead
map ... without using the result. btw the given code of op works.
I change it to reduce
@Satpal Why forEach? If reducing an array into an object, that's exactly what reduce is for
Your for loop is correct and you see it runs well. whats the problem? @blahblahvah
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);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.