Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to create a JavaScript object dynamically from two arrays of strings. One array is used for the key and another for the value. e.g. it should create *element.name="xyz";*etc

 var key=["name","id","surname"];
 var value=[["xyz","01","abc"],["def","02","ghi"]]; 
 var element=new Object();

from the above value it should create an object like this:

    var element=new Object();
    element.name="xyz";
    element.id="01";
    element.surname="abc";

    var element =new Object();
    element.name="def";
    element.id="02";
    element.surname="ghi";
share|improve this question
 
need more clarification about your needs –  Anup Sep 3 '13 at 11:30
 
Would element be an object or an array of objects? because your value object holds an array of 2 "objects" –  simdrouin Sep 3 '13 at 11:36
 
It looks like you are trying to create two objects, or perhaps two objects in an array there. –  Andy Sep 3 '13 at 11:37
 
@simdrouin its an array of objects –  Neerav Shah Sep 3 '13 at 11:37
 
@Andy i want to pass this object to array later –  Neerav Shah Sep 3 '13 at 11:38
show 3 more comments

2 Answers

up vote 2 down vote accepted

I would go like this :

var value=[["xyz","01","abc"],["def","02","ghi"]]; // notice it's an array of array instead of an array of objects

var elements = [];

for (var i = 0; i< value.length; i++) {
    var elem = new Object();
    for (var j=0; j< key.length; j++) {
        elem[key[j]] = value[i][j];
    }
    elements.push(elem);
}
share|improve this answer
 
thanks for your ans it really helped –  Neerav Shah Sep 3 '13 at 12:07
 
for sanity: j<key.length && j<value[i].length –  Emissary Sep 3 '13 at 12:09
 
can you help me to solve this problem also stackoverflow.com/q/18584226/2307391 –  Neerav Shah Sep 4 '13 at 4:25
add comment

Similar to the other answers but avoiding the inner loop:

var keys = ["name","id","surname"];
var values = [["xyz","01","abc"],["def","02","ghi"]]; // an array of arrays, not objects

function populateObjects(keys, values) {
  var arr = [];
  for (var i = 0, l = values.length; i < l; i++) {
    var obj = {};
    obj[keys[0]] = values[i][0];
    obj[keys[1]] = values[i][1];
    obj[keys[2]] = values[i][2];
    arr.push(obj);
  }
  return arr;   
}

var arr = populateObjects(keys, values);
console.log(arr);
share|improve this answer
 
However, if there is a new property added to the keys/values objects, you need to modify the populateObjects function –  simdrouin Sep 3 '13 at 11:54
 
Fair point. Question didn't mention that tho. It indicated the objects would be static. –  Andy Sep 3 '13 at 11:59
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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