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
asked Nov 24, 2016 at 6:34
Abdul Ghaffar
2383 silver badges14 bronze badges
-
1That's not JSON: What is the difference between JSON and Object Literal Notation?Andreas– Andreas2016年11月24日 06:46:34 +00:00Commented Nov 24, 2016 at 6:46
2 Answers 2
- Use
Bracket-notationto have variables as keys of object. Array#forEachcould 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!
answered Nov 24, 2016 at 6:37
Rayon
36.6k5 gold badges54 silver badges78 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Bryan Downing
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.Mahi
@BryanDowning it has to be equal otherwise how would he create object properties ?
Rayon
@BryanDowning — That is different story which is not mentioned in the OP. I have highlighted it in the Note though :)
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>
Comments
lang-js