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:
- how to generate resultant array ?
- can i access the properties as:
dealers.RequestQuote?
asked Feb 19, 2015 at 10:00
Chintan Soni
25.4k26 gold badges113 silver badges177 bronze badges
3 Answers 3
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
Sign up to request clarification or add additional context in comments.
Comments
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,
}
}
answered Feb 19, 2015 at 10:04
joews
30.4k11 gold badges82 silver badges91 bronze badges
Comments
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);
answered Feb 19, 2015 at 10:06
Naeem Shaikh
15.8k8 gold badges53 silver badges92 bronze badges
4 Comments
Chintan Soni
When I tried your solution with some modifiction, I got
[{"x":{"RequestQuote":false,"PlaceOrder":false}},{"x":{"RequestQuote":false,"PlaceOrder":false}}]Chintan Soni
I did
console.log(JSON.stringify(result)); to see the outputNaeem Shaikh
@ChintanSoni create a fiddle of it, what i wrote is according to the requirement you asked in the question
Chintan Soni
Yes. Just a little correction with your answer. I wanted
"dealers" , "builders" instead of "x"lang-js
[ "dealers" : { "RequestQuote" : false, "PlaceOrder" : false, }, "builder" : { "RequestQuote" : false, "PlaceOrder" : false, } ]would not be a array.Array does not have key-value pair. You probably want to have Array of Objects like[ {"dealers" : { "RequestQuote" : false, "PlaceOrder" : false, }}, {"builder" : { "RequestQuote" : false, "PlaceOrder" : false, }} ]arrayCompanyUsers