Abdul Ghaffar Abdul Ghaffar - 9 days ago 5
Javascript Question

Creating a JSON dynamically

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

Answer

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!

Comments