Chintan Soni
Chintan Soni

Reputation: 25267

javascript : create objects dynamically

Ok. I want to create a JSON array dynamically. Case is:

Lets say, I have array:

var arrayCompanyUsers = ["dealers", "builders"];

From the above array, I want to generate another array as below:

[
    "dealers" : {
                  "RequestQuote" : false,
                  "PlaceOrder" : false,
                 },
    "builder" : {
                  "RequestQuote" : false,
                  "PlaceOrder" : false,
                 }
]

Two questions:

  1. how to generate resultant array ?
  2. can i access the properties as: dealers.RequestQuote ?

Upvotes: 1

Views: 77

Answers (3)

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

see this : http://jsfiddle.net/zL5x6xxm/3/

 var arrayCompanyUsers = ["dealers", "builders"];
var result=[];
for(i=0;i<arrayCompanyUsers.length;i++)
{var x=arrayCompanyUsers[i]
    result.push('{'+ x+':{  "RequestQuote" : false, "PlaceOrder" : false, }}');  
}

console.log(result);

Upvotes: 1

joews
joews

Reputation: 30330

You could use Array.prototype.map to create an array of objects:

var output = arrayCompanyUsers.map(function(key) {
  var record = {};
  record[key] =  {
    RequestQuote : false,
    PlaceOrder : false,
  }

  record data;
})

To get RequestQuote for the "dealers" record:

function getValue(records, name, value) {
  var matches = records.filter(function(record) {
      return record[name] !== undefined;
    })

    if(matches.length > 0) {
      return matches[0][name][value];
    }
}

console.log(getValue(output, 'dealers', 'RequestQuote'));
// -> false

As an aside, your data would be easier to work with if you used the format:

{
  name: "dealers",
  properties: {
    RequestQuote : false,
    PlaceOrder : false,
  }
}

Upvotes: 1

Simon
Simon

Reputation: 230

You can do this with the following snipped:

var arrayCompanyUsers = ['dealers', 'builders'];
var target = {};
for (var i = 0; i < arrayCompanyUsers.length; i++){
    var user = arrayCompanyUsers[i];
    target[user] = {
        'RequestQuote' : false,
        'PlaceOrder' : false,
    };
}
console.log(target);

And yes, you should be able to access the properties with dealers.RequestQuote

Upvotes: 2

Related Questions