动态创建JSON

时间:2016-11-24 06:34:46

标签: javascript arrays json

在js中我有

var codedata = ["sku1","sku12","sku123"];
var pricedata = ["2.18","2.45","3.67"];
var head = 'storepricing';

我想要一些像这样的东西

var jsonData = { "storepricing" :{"sku1": "2.18", "sku12": "2.45", "sku123": "3.67"}}; 

codedata pricingata 不是静态的

2 个答案:

答案 0 :(得分: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);

注意:假设codeDatapriceData的长度相等!

答案 1 :(得分:1)

这就是你想要的...... 但请记住,变量codedata和pricingata的长度必须相同。

// 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>