0

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

Abdul Ghaffar
  • 228
  • 3
  • 14
  • 1
    That's not JSON: [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Nov 24 '16 at 06:46

2 Answers2

7

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!

Rayon
  • 36,219
  • 4
  • 49
  • 76
  • 2
    This will work as long as you can be sure that `codedata` and `pricedata` always have the same number of items, and the order of the items in each array match up. – Bryan Downing Nov 24 '16 at 06:42
  • @BryanDowning it has to be equal otherwise how would he create object properties ? – Mahi Nov 24 '16 at 06:49
  • 1
    @BryanDowning — That is different story which is not mentioned in the OP. I have highlighted it in the _Note_ though :) – Rayon Nov 24 '16 at 06:50
1

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>