1

I want to put an array into an object with two keys (key, val). This is my code.

var arr = ["hello", "44", "thanks", "32"];

console.log(arr);
console.log(arr.length);

var obj = {};

for (var i = 0; i < arr.length; i++) {
    obj.key = arr[i];
}

console.log(obj);

this is the result i would like to have.

obj[0] = {key: "hello", val: "44"}; 
obj[1] = {key: "thanks", val: "32"}; 

Thanks allot!

2 Answers 2

2

So, what you want is a loop every 2 item instead of 1, and then take the current item and the next one.

Maybe something like this :

obj = [];
for (var i = 0; i < arr.length; i=i+2) {
  obj.push({key:arr[i], val:arr[i+1]});
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, thats the one I was looking for.
0

How about you try underscorejs

http://underscorejs.org/#object

1 Comment

This should better be a comment instead of answer

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.