How to push a value in an array - javascript

i want to know how can i store data in an array like that in order to do it with push function.
here is the code
var data_array = [];
and data look like that
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
any help to change this way of inserting and use push function .

May be this will help,
You can loop through all the keys of the object and push each one into the array
var data_array = [];
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
var keysArray = Object.keys(my_data);
keysArray.forEach(function(key, index) {
data_array.push({ key : my_data[key]});
});
console.log(data_array);

Try this (wrap data in curly braces):
data_array.push( {"2011":{"name":"Team Leaders","total":93,"drilldown":"true"} })

I don't know Exactly what do you want. Anyway, I think that It works for you.
var personInfo = new Object();
var my_data = new Object();
personInfo.name = 'Team Leaders';
personInfo.total = 93;
personInfo.drilldown = 'true';
my_data.person1 = personInfo;
my_data.person2 = personInfo;
// confirm
var jsonType = JSON.stringify(my_data);
console.log(jsonType);

I think this is what you need
var data_array = [];
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
var data_keys= Object.keys(my_data);
data_keys.forEach(function(key, index) {
var obj = {};
obj[key] = my_data[key];
data_array.push(obj);
});

Related

How to initialize an array of objects inside of another array of objects?

I have a question. How can I initialize my var ingredientes = []; inside of the object "receita"? Is it done like I did? Or do I have to initialize it inside instead of outside?
var receitas = [];
var ingredientes = [];
var ingrediente = {
constructor: function(aNome, aQuantidade){
this.nome=aNome;
this.quantidade=aQuantidade;
}
};
var receita = {
constructor: function(aTipo, aNome, aTempo, aCusto, aDificuldade,
aDescricao, aIngredientes){
this.nome=aNome;
this.tipo=aTipo;
this.tempo=aTempo;
this.custo=aCusto;
this.dificuldade=aDificuldade;
this.descricao=aDescricao;
this.ingredientes=aIngredientes;
}
}
Thanks for any response!
I guess what you're actually looking for are classes, try doing this;
var receitas = [];
var ingredientes = [];
class Receita {
constructor(aTipo, aNome, aTempo, aCusto, aDificuldade, aDescricao, aIngredientes) {
this.nome = aNome;
this.tipo = aTipo;
this.tempo = aTempo;
this.custo = aCusto;
this.dificuldade = aDificuldade;
this.descricao = aDescricao;
this.ingredientes = aIngredientes;
}
}
class Ingrediente {
constructor(aNome, aQuantidade) {
this.nome = aNome;
this.quantidade = aQuantidade;
}
}
So to add an ingrediente to the ingredientes array you should do something like this:
var newReceita = new receita('Bolo', 'Bolo de fubá');
ingredientes = [
new ingrediente('Farinha', 300),
new ingrediente('Ovos', 2)
]
receita.ingredientes = ingredientes;
receita.constructor(...) will create all the properties within receita.

How to get multiple named querystring values in jQuery/Javascript?

I've got the following parameters
/Search?category=1&attributes=169&attributes=172&attributes=174&search=all
I'm trying to get just the attributes querystring values as an array in javascript, for example.
attributes = ['169','172','174']
Bearing in mind there may be other parameters that are irrelevant such as search or category.
Might not the proper answer but just tried
var str = "/Search?category=1&attributes=169&attributes=172&attributes=174&search=all";
var str1 = str.split("&");
var attributesArray = [];
for(var i=0; i<str1.length; i++) {
if (str1[i].includes("attributes")) {
attributesArray.push(str1[i].replace("attributes=", ""));
}
}
Fiddle https://jsfiddle.net/5Lkk0gnz/
You can do it like this:
(function() {
function getJsonFromUrl(url) {
var query = url.substr(1);
var arr = [];
query.split("&").forEach(function(part) {
var item = part.split("=");
arr.push(decodeURIComponent(item[1]));
});
return arr;
}
var url = "https://example.com?category=1&attributes=169&attributes=172&attributes=174&search=all";
var params = getJsonFromUrl(url);
console.log(params);
})();
Hope this helps!
This should do what you want, assuming you already have your url:
var url = "/Search?ategory=1&attributes=169&attributes=172&attributes=174&search=all";
var attrs = url
.match(/attributes=\d*/g)
.map(function(attr){
return Number(attr.replace("attributes=", ""));
});
console.log(attrs); //=> [169, 172, 174]

Add items to local storage across multiple pages

There are two files. The first:
<div class="someclass">text1</div>
<div class="someclass">text2</div>
<script>
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.innerHTML;
});
localStorage.foobar = JSON.stringify(arr);
alert(localStorage.foobar);
</script>
That gives: ["text1","text2"]
The second (files are identical except inner text in first two lines):
<div class="someclass">text3</div>
<div class="someclass">text4</div>
<script>
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.innerHTML;
});
localStorage.foobar = JSON.stringify(arr);
alert(localStorage.foobar);
</script>
That gives: ["text3","text4"]
I would like the second file to give ["text1","text2","text3","text4"], or maybe ["text3","text4","text1","text2"].
How can I do that?
You need to retrieve the previously-stored data (if any), and append to that array. Something like:
var foostr = localStorage.foobar || "[]";
arr = JSON.parse(foostr);
var foo = document.getElementsByClassName("someclass");
Array.prototype.forEach.call(foo, function(elem) {
arr.push(elem.innerHTML);
});
localStorage.foobar = JSON.stringify(arr);
alert(localStorage.foobar);
So you need to see if there is anything and concatenate it to the array.
if (localStorage.foobar) {
var prev = JSON.parse(localStorage.foobar);
arr = arr.concat(prev);
}
localStorage.foobar = JSON.stringify(arr);
You can concat the both arrays after retrieving localStorage's contents first, using JSON.parse():
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.innerHTML;
});
localStorage.foobar = JSON.stringify(JSON.parse(localStorage.foobar).concat(arr));
console.log(localStorage.foobar);

Automatically push / nest object within a parent object in JavaScript

I am currently working on an excel like behaviour for some task.
All "tr"s are bound to the variable $test
var $test = $('tbody tr');
Now I use the jQuery .each function to run throuhg all trs and collect its relevant contents like this :
$test.each(function(index, element){
var $row_id = $(this).data("rowid");
var status = $(this).find('#status option:selected').val();
var ma_name = $(this).find('#ma-name').val();
var datum = $(this).find('#datum').val();
var firmenname1 = $(this).find('#firmenname1').val();
var firmenname2 = $(this).find('#firmenname2').val();
var limit = $(this).find('#limit').val();
var gruppe_kredit = $(this).find('#gruppe_kredit').val();
var omv_kdnr = $(this).find('#omv_kdnr').val();
var sap_kdnr = $(this).find('#sap_kdnr').val();
var fos = $(this).find('#fos').val();
var hga_kdnr = $(this).find('#fos').val();
var pushObj = {row_id: $row_id,....};
});
Since the pushObject gets greated and stuffed with content each time the each function gets executed I need a way to "push" this object into a parent object which I can later use with AJAX.
The behaviour I'd wish for would be like this:
var parentObj = {};
$.each(function(){
// in each run the newly created object gets nested into the parentObject which results in the parent object having X-childObjects
});
So after, lets say 5 each runs, the parentObj should contain : [0],[1],...,[4] objects.
Could anyone guide me throuhg that process ?
Try this solution by storing pushObj inside array variable like so :
// add here
var parentObj = [];
$test.each(function (index, element) {
var $row_id = $(this).data("rowid");
var status = $(this).find('#status option:selected').val();
var ma_name = $(this).find('#ma-name').val();
var datum = $(this).find('#datum').val();
var firmenname1 = $(this).find('#firmenname1').val();
var firmenname2 = $(this).find('#firmenname2').val();
var limit = $(this).find('#limit').val();
var gruppe_kredit = $(this).find('#gruppe_kredit').val();
var omv_kdnr = $(this).find('#omv_kdnr').val();
var sap_kdnr = $(this).find('#sap_kdnr').val();
var fos = $(this).find('#fos').val();
var hga_kdnr = $(this).find('#fos').val();
var pushObj = {
row_id: $row_id,
....
};
// add here
parentObj.push(pushObj);
});
// later on here access parentObj variable

jQuery convert data-* attributes to lower camel case properties

I have the following jQuery script to intialise a jQuery plugin called poshytips. I want configure the plugin using Html5 data attributes. I am repeating myself big time, can anyone come up with a better way to do this?
$('.poshytip-trigger').each(function (index) {
var $this = $(this);
var data = $this.data();
var options = {};
if (data['class-name']) {
options.className = data['class-name'];
}
if (data['align-x']) {
options.alignX = data['align-x'];
}
if (data['align-y']) {
options.alignY = data['align-y'];
}
if (data['offset-y']) {
options.offsetY = data['offset-y'];
}
if (data['offset-x']) {
options.offsetX = data['offset-x'];
}
$this.poshytip(options);
});
I would use a for..in loop to read the data-* tags.. Also you don't need to camelcase as jQuery converts it to camelCase internally... Source code reference.
$('.poshytip-trigger').each(function (index) {
var $this = $(this);
var data = $this.data();
var options = {};
for (var keys in data) {
options[keys] = data[keys];
}
// For older versions of jQuery you can use $.camelCase function
for (var keys in data) {
options[$.camelCase(keys)] = data[keys];
}
});
DEMO
for jQuery 1.4.4,
$('.poshytip-trigger').each(function(index) {
var $this = $(this);
var data = $this.data();
var options = {};
for (var keys in data) {
options[camelCase(keys)] = data[keys];
}
});
//copied from http://james.padolsey.com/jquery/#v=git&fn=jQuery.camelCase
function camelCase(str) {
return str.replace(/^-ms-/, "ms-").replace(/-([a-z]|[0-9])/ig, function(all, letter) {
return (letter + "").toUpperCase();
});
}
DEMO for 1.4.4
Something like this - It does convert offset-x to offsetX:
http://jsfiddle.net/8C4rZ/1/
HTML:
<p data-test="sdsd" data-test2="4434"></p>​
JavaScript:
$(document).ready(function() {
var options = {};
for (var key in $("p").data()) {
options[key] = $("p").data(key);
}
console.log(options);
});​
But I think Daniel's approach is better, since he explicitly controls which attributes gets set. This will take all data- attributes.
var names = ["className", "alignY", ...];
$(names).each(function(ind, name){
var dataName = name.replace(/[A-Z]/, function(letter){
return letter.toLowerCase();
});
if(data[dataName]){
options[name] = data[dataName];
}
});
Does this work? Unlike the other answers, this piece of code both convert only explicitly set attributes and keeps the options-object attribute name camelCase.
Try using a for in loop.
var array = ['class-name', 'align-x', 'align-y', 'offset-y', 'offset-x'];
for (x in array) {
if(data[array[x]]) {
options[array[x]] = data[array[x]];
}
}
Update: In response to the OP's clarification, he could write something like this:
var Pair = function(hyphenated, camcelCased) {
this.hyphenated = hyphenated;
this.camelCased = camelCased;
}
var array = [
new Pair('class-name', 'ClassName'),
new Pair('align-x', 'alignX'),
new Pair('align-y', 'alignY'),
new Pair('offset-x', 'offsetX'),
new Pair('offset-y', 'offsetY')];
var i, optionNameHyphenated, optionNameCamelCased;
for(i = 0; i < array.length; i++) {
optionNameHyphenated = array[i]['hyphenated'];
optionNameCamelCased = array[i]['camelCased'];
if (data[optionNameHyphenated]);
options[optionNameCamelCased] = data[optionNameHyphenated];
}

Categories

Resources