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

asked Nov 24, 2016 at 6:34
1

2 Answers 2

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!

answered Nov 24, 2016 at 6:37
Sign up to request clarification or add additional context in comments.

3 Comments

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.
@BryanDowning it has to be equal otherwise how would he create object properties ?
@BryanDowning — That is different story which is not mentioned in the OP. I have highlighted it in the Note though :)
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>

answered Nov 24, 2016 at 7:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.