Create JSON with multiple values - javascript

I need to create a JSON with data every time I click on a button BTN. Here is how I create my JSON :
$(document).ready(function () {
var maj = {};
$("#btnSubmitRejetRefModele").click(function() {
maj['one'] = 'a'
maj['two'] = 'b'
maj['three'] = 'c'
}
Values a,b,c are changing every time and I want to store each value in a JSON with the structure :
maj = {
"0" : {'one':'a','two':'b','three':'b'} ,
"1" : {'one':'a2','two':'b2','three':'c2},
// ...
}
How can I code and append my data in my JSON each time I click on the button. This JSON will be used in a post method to insert values into PGsql

You need to check the size of the current object, and insert the data to the position of that size:
$(document).ready(function() {
var maj = {};
$("#btnSubmitRejetRefModele").click(function() {
var size = Object.keys(maj).length;
var data = {
one: 'a' + (size+1),
two: 'b' + (size+1),
three: 'c' + (size+1)
}
maj[size] = data;
console.clear();
console.log(maj);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnSubmitRejetRefModele">Add</button>
If you need an alternative, here's my original answer, which is using an array of objects, you can use it later as maj[0], maj[1], and so on:
$(document).ready(function() {
var maj = [];
$("#btnSubmitRejetRefModele").click(function() {
var data = {
one: 'a',
two: 'b',
three: 'c'
}
maj.push(data);
console.clear();
console.log(maj);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnSubmitRejetRefModele">Add</button>
This is not exactly the format you need, but maybe helps.

An alternative could be storing it in an array.
let data = {
myArray: [{'one':'a','two':'b','three':'b'}]
}
Then every time you can just add data by adding to that array.
data.myArray.push({'one':'a2','two':'b2','three':'b2'})
Advantage, no need to keep track of any counter variables.
Disadvantage, removing things from the array might be less performant or less convenient. But that depends on the use case.
Readability is the most important thing when writing code you want to maintain.

You should keep track of button clicks count, and use it when creating the new part of your JSON object.
var maj = {};
var counter = 0;
$("#btnSubmitRejetRefModele").click(function() {
var temp = {}
temp['one'] = aNewValue
temp['two'] = bNewValue
temp['three'] = cNewValue
maj[counter++] = temp
}
but finally, I recommend you to use an array instead of an object(it's already indexed)
just push your new created objects in it and whenever you wanted to convert it to an object, do this:
myObject = Object.assign({}, maj);

Related

adding object to array using .splice()

I have a problem adding the object "myobj" to the arrays data / data2. As you see "myobj" a JS object which I would like to add to either data or data2. the functions are being triggered by clicks on different buttons.
console.log of myobj shows me
{ array: "arr_id_1", axis: "x", acc: "", vel: "", dist: "", jerk: "" }
I receive an error saying data2.splice() is not a function.
which is the format I need. "myobj" is supposed to be added to an array which I want to use JSON.stringify on. This JSON literal goes then to a python script via ajax. The array "data" is being filled with each click I perform correctly but not in the format for further processing. So I tried to fill array data2 since I have read that I could use .splice() as well. Unfortunately, console.log(data2) shows "undefined" for each field I try to fill and I have no idea how to solve it.
I tried to use JSON.stringify on "myobj" and as another attempt, I have tried to JSON.parse it back again. I tried adding the brackets and colons into quotes but no success either.
I am grateful for any advice or help.
var counterx = 0;
let data = [];
let data2 = {};
function valuesX() {
counterx++;
// does something here
let arr_id = [];
arr_id.name = 'arr_id_' + counterx;
let ind = counterx - 1;
let myobj;
function arr() {
var ind = sel.selectedIndex;
var axis = sel.options[ind].text;
arr_id.length = 0;
arr_id.push(arr_id.name, axis, btna.value, btnv.value, btns.value, btnj.value)
myobj = {
array: arr_id[0],
axis: arr_id[1],
acc: arr_id[2],
vel: arr_id[3],
dist: arr_id[4],
jerk: arr_id[5]
};
console.log(arr_id.name, arr_id)
console.log(myobj)
console.log(data.name, data)
console.log(data2.name, data2)
}
data.name = 'data';
data2.name = 'data2';
data.splice(ind, 0, arr_id)
data2.splice(ind, 0, myobj)
}
SOLUTION:
I have converted the myobj to an object using Answer from JVE999, first suggestion and used .splice() to add the every new myobj to the array data. I have used splice because I need to overwrite already existing elements while keeping the order (Thus the indx) when I trigger the function (.splice() reference).
var arr_id = [];
arr_id.name = 'arr_id_'+counterx;
var myobj;
var indx = counterx-1;
var data_new;
data.name = 'data';
function arr(){
var ind = sel.selectedIndex;
var axis = sel.options[ind].text;
arr_id.length = 0;
arr_id.push(arr_id.name, axis, btna.value, btnv.value,btns.value, btnj.value)
myobj = {
array:arr_id[0],
axis:arr_id[1],
acc:arr_id[2],
vel:arr_id[3],
dist:arr_id[4],
jerk:arr_id[5]
};
data_new = convArrToObj(myobj);
data.splice(indx, 1, data_new)
data_str = JSON.stringify(data)
console.log(data.name, data)
console.log(data_str)
}

How to create multiple objects based on dynamic data?

Basically what i'm doing, is trying to create my own steam market JSON, by HTML parsing.
Example of how I'm currently doing that :
var url = 'http://steamcommunity.com/market/search?appid=730'
var itemDiv = $("<div></div>")
$.get(url).success(function(r){
data = $(r).find('stuff i need')
itemDiv.append(data)
})
and now say I wanted to find names of the items in the div, i would do something like :
itemDiv.find('x').each(function(){
var name = $(this).find("y").text()
// console.log(name) [or do whatever is needed ect]
})
As I mentioned before, I need to return objects based on that data in the format of:
var item = {name:"",price:0}
However, things like price will always be changing.
Based on the data thats in the div, the final product would look along the lines of :
var x = {name:"a",price:1}
var x2 = {name:"a2",price:2}
How do I go about doing this? I thought maybe i could store the data in an array, and then do something like
for(x in y){
return object
}
or something along those lines.
Sorry if this seems like a bonehead question, I'm pretty new to javascript.
clarification: i'm trying to figure out how to return multiple objects based on the data inside the div.
Here is the code that builds an array of objects based on two arrays (assuming they are of equal length).
function buildStocks() {
// Names and prices can also be passed as function arguments
var names = ['a', 'b', 'c'];
var prices = [1, 2, 3];
var result = []; // Array of these objects
for (var i = 0; i < names.length; i++) {
result.push({
name: names[i],
price: prices[i]
});
}
return result;
}

Iterate through Id's, store values, put into an array

I want to be able to iterate through a number of ids called "#option1", "#option2" etc. The problem is its for an interactive form and I don't know how many options there will be. So I need a way to iterate through the amount in the DOM when the user clicks ("#dothis").
Then I need to get the values of the those options, put into an array called arraylist.
$("#doThis").on("click", function() {
var optionone = $("#option1").val();
var optiontwo = $("#option2").val();
var optionthree = $("#option3").val();
var optionfour = $("#option4").val();
var optionfive = $("#option5").val();
var arrayList = [optionone, optiontwo, optionthree,
optionfour, optionfive];
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
}); // end of dothis click event
As Andy said, give every option the same class. In my example it's "option-item".
$("#doThis").on("click", function() {
var arrayList = [];
$('.option-item').each(function(i) {
arrayList[i] = $(this).val();
});
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
});
Every value is now stored in the array.
see fiddle.
greetings timmi
With your code as is, you can use a selector that selects everything with an ID that starts with 'option', like so [id^="option"], here's how to use it:
$("#doThis").on("click", function () {
var arrayList = [];
$('[id^="option"]').each(function (index, element) {
arrayList.push($(element).val() );
});
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
}); // end of dothis click event

creating nested array javascript

Have looked at many examples but cant seem to get to make an nested array to store some data nicely. How can I get the following code to work? It gives me an error now:
var shipdata = [];
shipdata['header']['bedrijfsnaam'] = $('[name="bedrijfsnaam"]').val();
shipdata['header']['naam'] = $('[name="naam"]').val();
shipdata['header']['straat'] = $('[name="straat"]').val();
shipdata['header']['postcode'] = $('[name="postcode"]').val();
shipdata['header']['plaats'] = $('[name="plaats"]').val();
shipdata['header']['telefoon'] = $('[name="telefoon"]').val();
shipdata['header']['email'] = $('[name="email"]').val();
shipdata['header']['instructies'] = $('[name="instructies"]').val();
shipdata['header']['ordernummertje'] = $('[name="ordernummertje"]').val();
$(".pakketten").each(function(index, element) {
index++;
shipdata['pakketten']['pakket'+index]['lengte'] = $('[name="lengte'+index+'"]').val(),
shipdata['pakketten']['pakket'+index]['breedte'] = $('[name="breedte'+index+'"]').val(),
shipdata['pakketten']['pakket'+index]['hoogte'] = $('[name="hoogte'+index+'"]').val(),
shipdata['pakketten']['pakket'+index]['gewicht'] $('[name="gewicht'+index+'"]').val()
});
Probably im doing this all wrong, but some pointers would be welcome.
Thanks!
First of all, you are creating an object and not an array, so use {} instead of [] for the main container.
Second, when inserting multiple values at the same time, you can use a much more compact notation:
var shipdata = {
'header': {
'bedrijfsnaam': $('[name="bedrijfsnaam"]').val(),
'naam': $('[name="naam"]').val()
'...': '...'
},
'pakketten': []
};
$(".pakketten").each(function(index, element) {
shipdata['pakketten'].push({
'lengte': $('[name="lengte'+index+'"]').val(),
'breedte': $('[name="breedte'+index+'"]').val(),
'...': '...'
});
});
Besides, anytime you want to access an object or array in any way, you have to initialize it beforehand as already mentioned by #antyrat.
You need to create objects each time you want to have nested array:
var shipdata = {};
shipdata['header'] = {};
shipdata['header']['bedrijfsnaam'] = $('[name="bedrijfsnaam"]').val();
//...
shipdata['pakketten'] = {};
$(".pakketten").each(function(index, element) {
index++;
shipdata['pakketten']['pakket'+index] = {};
shipdata['pakketten']['pakket'+index]['lengte'] = $('[name="lengte'+index+'"]').val(),
// ...
Answer updated due to comments as arrays didn't have string indexes.

Push to array a key name taken from variable

I have an array:
var pages = new Array();
I want to push my pages data to this array like this:
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
pages_order.push({datatype:info});
});
but this code doesn't replace datatype as variable, just puts datatype string as a key.
How do I make it place there actual string value as a key name?
I finally saw what you were trying to do:
var pages = new Array();
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
var temp = {};
temp[datatype] = info;
pages_order.push(temp);
});
$('li.page').each(function () {
//get type and info, then setup an object to push onto the array
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
obj = {};
//now set the index and the value for the object
obj[datatype] = info;
pages_order.push(obj);
});
Notice that you can put a comma between variable declarations rather than reusing the var keyword.
It looks like you just want to store two pieces of information for each page. You can do that by pushing an array instead of an object:
pages_order.push([datatype, info]);
You have to use datatype in a context where it will be evaluated.
Like so.
var pages = [];
$('li.page').each(function () {
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
record = {};
record[datatype] = info;
pages_order.push(record);
});
You only need one var it can be followed by multiple assignments that are separated by ,.
No need to use new Array just use the array literal []
You may add below single line to push value with key:
pages_order.yourkey = value;

Categories

Resources