确定。我想动态创建一个JSON数组。案例是:
让我们说,我有阵列:
var arrayCompanyUsers = ["dealers", "builders"];
从上面的数组中,我想生成另一个数组,如下所示:
[
"dealers" : {
"RequestQuote" : false,
"PlaceOrder" : false,
},
"builder" : {
"RequestQuote" : false,
"PlaceOrder" : false,
}
]
两个问题:
dealers.RequestQuote
?答案 0 :(得分:2)
您可以使用以下剪辑执行此操作:
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);
是的,您应该能够使用dealers.RequestQuote
答案 1 :(得分:1)
您可以使用Array.prototype.map
创建一个对象数组:
var output = arrayCompanyUsers.map(function(key) {
var record = {};
record[key] = {
RequestQuote : false,
PlaceOrder : false,
}
record data;
})
为#34;经销商&#34;获取RequestQuote
记录:
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
另外,如果您使用以下格式,您的数据将更容易使用:
{
name: "dealers",
properties: {
RequestQuote : false,
PlaceOrder : false,
}
}
答案 2 :(得分:1)
请参阅: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);