Reputation: 238
In js I have
var codedata = ["sku1","sku12","sku123"];
var pricedata = ["2.18","2.45","3.67"];
var head = 'storepricing';
I want some thing like this
var jsonData = { "storepricing" :{"sku1": "2.18", "sku12": "2.45", "sku123": "3.67"}};
codedata and pricedata are not static
Upvotes: 0
Views: 85
Reputation: 38
this is what you want .. but rememmber, the length of variable codedata and pricedata must be same.
// NOTE : length of variable codedata must same with legth variable pricedata
//var myJsonString = JSON.stringify(yourArray);
var codedata = ["sku1","sku12","sku123"];
var pricedata = ["2.18","2.45","3.67"];
var head = 'storepricing';
function cJSONCustom(header,attr,val){
var ArrJS = {};
var ArrJSON = {};
for(var i = 0; i < attr.length;i++){
var name = attr[i];
var value = val[i];
ArrJS[name] = value;
}
ArrJSON[header]=ArrJS;
console.log(ArrJSON);
$('#result').html(JSON.stringify(ArrJSON));
}
cJSONCustom(head,codedata,pricedata);
<!--
Dinamically generate JSON data from array.
Created by : AchmaDesigner
-->
<p id="result"></p>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
Upvotes: 1
Reputation: 36609
Bracket-notation
to have variables as keys of object.Array#forEach
could be used to iterate array.var codedata = ["sku1", "sku12", "sku123"];
var pricedata = ["2.18", "2.45", "3.67"];
var head = 'storepricing';
var jsonData = {};
jsonData[head] = {};
codedata.forEach(function(key, index) {
jsonData[head][key] = pricedata[index];
});
console.log(jsonData);
Note: Length of both codeData
and priceData
assumed to be equal!
Upvotes: 7