How to create a nested array using javascript to get multiple bill? - javascript

I want to get a nested array of multiple bills using javascript. Below i am pasting the sample of the inputs that we get
var out = [{"tax":"CGST#9%","percent":"106.78"},{"tax":"SGST#9%","percent":"106.78"},{"tax":"SGST#2.5%","percent":3.57},{"tax":"CGST#2.5%","percent":3.57}];
var name = Sarath H;
var mobile = 9916751978;
var payment = Paytm;
var products = [{"product_code":"AMO-73","item":"AM VG Credit-5","quantity":"1","price":"1000","price_display":"847.46","tax":"18","taxgroup_name":"GST#18%","tax_linked":",25,26"},{"product_code":"AMO-77","item":"Roller coaster","quantity":2,"price":"200","price_display":"169.49","tax":"18","taxgroup_name":"GST#18%","tax_linked":",25,26"},{"product_code":"AMO-78","item":"Dancing car","quantity":"1","price":"150","price_display":"142.86","tax":"5","taxgroup_name":"GST#5%","tax_linked":",29,30"}];
var tax = [{"tax":"CGST#9%","percent":"76.27"},{"tax":"SGST#9%","percent":"76.27"},{"tax":"CGST#9%","percent":"30.51"},{"tax":"SGST#9%","percent":"30.51"},{"tax":"SGST#2.5%","percent":"3.57"},{"tax":"CGST#2.5%","percent":"3.57"}]
var total = 1550.00;

you can create array of objects like
var bills = [
{
address: 'bil1',
billdate: '',
....
data_product: [
{
adssd: 'asdas'
....
}
....
],
.....
}, {
address: 'bil2',
billdate: '',
....
data_product: [
{
adssd: 'asdas'
}
],
...
}
]
This is what you need? Otherwise provide more description

Related

JS converting an array to a json linked list?

I am new to JS and the concepts of organising data elude me a little, trying to take data from a specific array format (as this is what I have to work with) and output it into another specific JSON format.
This is to pass data to the D3 sankey module
https://github.com/d3/d3-plugins/blob/master/sankey/sankey.js
I can't figure out is how to add the index of the node into the links, rather than the name.
Really I am just totally lost with it!
I made a fiddle here:
https://jsfiddle.net/adamdavi3s/kw3jtzx4/
Below is an example of the data and the output required
var data= [
{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var output= {
"nodes":[
{"name":"Agricultural 'waste'"},
{"name":"Bio-conversion"},
{"name":"Electricity grid"},
{"name":"Losses"},
{"name":"Liquid"}
],
"links":[
{"source":0,"target":1,"value":124.729},
{"source":1,"target":2,"value":0.597},
{"source":1,"target":3,"value":26.862},
{"source":1,"target":4,"value":280.322},
{"source":3,"target":4,"value":280.322}
]
};
Here is my code from the fiddle thusfar
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source};
var found = jQuery.inArray(node, sourceArray);
if (found < 0) {
// Element was not found, add it.
sourceArray.push(node);
}
}
console.log(sourceArray);
In javascript:
[ ] annotations are used to describe an Array, like:
var names=["John","Lisa"]
{ } Its are used to describe an Object
var person = {"name" : "John", "age" : 23}
You can use them inside one another
var people=[{"name" : "John", "age" : 23},{"name" : "Lisa", "age" : 44}]
Try this:
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
var linkArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source,};
var link= {
"source":i,
"target":data[i].target,
"value":data[i].value,
};
var found = jQuery.inArray(node, sourceArray);
if (found >= 0) {
// Element was found, remove it.
sourceArray.splice(found, 1);
linkArray.splice(found, 1);
} else {
// Element was not found, add it.
sourceArray.push(node);
linkArray.push(link);
}
}
finalArray={"nodes": sourceArray,"links": linkArray}
console.log(finalArray);
https://jsfiddle.net/9x4rdyy7/
Array.reduce() is perfect for this use case ;)
Take a look.
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var output = data.reduce(function(result, item){
for(key in search = ['source','target']) {
var value = item[search[key]];
if(! result.index.hasOwnProperty(value)){
result.index[value] = Object.keys(result.index).length;
result.nodes.push({name: value});
}
}
result.links.push({
source: result.index[item.source],
target: result.index[item.target],
value: Number(item.value)
});
return result;
}, {nodes: [], links: [], index: {}});
delete output.index;
console.log(output);

how to get dynamically created object inserted into another object

Good morning!
i have two dynamically created objects using form fields values. They are object literals which look like this:
var courses = {};
course['name'] = $('#course').val();
var students = {};
students['first'] = $('#first_name').val();
students['last'] = $('#last_name').val();
students['age'] = $('age').val();
I would like to insert them in a single object literal var person= {}
i need the two objects into one because I need to stringify it and send via ajax to my process page. Could you please help me?
You can populate an object as you are creating it:
var persons = {
courses: {
name: $('#course').val(),
},
students: {
name: $('#first_name').val(),
last: $('#last_name').val(),
age: $('#age').val(),
},
};
If you want to use the objects that you already have then you can do so:
var persons = {
courses: courses,
students: students,
};
You can create a object with the 2 objects like:
var data = {courses:courses,students:students};
or you can append one to the other
students['courses'] = courses;
And what's the problem?
Just place these objects into your object and then you can serialize it e.g. to JSON and send via ajax:
var person = {}
person.course = {};
person.student = {};
person.course['name'] = "Course 1";
person.student['first'] = "Vasya";
person.student['last'] = "Pupkin";
person.student['age'] = "26";
If you want multiple students, you should use arrays. Here we create an array with 3 objects, each represents a student:
var person = {}
person.course = {};
person.students = [{},{},{}];
person.course['name'] = "Course 1";
person.students[0]['first'] = "Vasya";
person.students[0]['last'] = "Pupkin";
person.students[0]['age'] = "26";
person.students[1]['first'] = "Petya";
person.students[1]['last'] = "Vasechkin";
person.students[1]['age'] = "30";
person.students[2]['first'] = "Vasiliy";
person.students[2]['last'] = "Alibabaevich";
person.students[2]['age'] = "40";
You can do the same thing with courses.
But in this case the name person for the object that contains all this data a bit confusing, because it contains multiple students. You should give meaningful names for your variables.

How to link one array value to another array values?

I have an array called category.
var category = ["automobile","Fashion","Music Instruments"]
and I need to link this array with the below array according to product.
var products = ["LandRover","Guitar","vintage,"Drums","Maserati","Piano"]
I think you are talking about some stuff like this?...
//variables predefined
var category = ["Automobile","Fashion","Music Instruments"]
var products = ["LandRover","Guitar","vintage","Drums","Maserati","Piano"]
//create a object categories where later we will add our products!
var categories = { };
//add values(category & products)
categories[ category[0] ] = [ products[0] , products[4] ]; //Automobile
categories[ category[1] ] = [ products[2] ]; //Fashion
categories[ category[2] ] = [ products[1] , products[3] ,products[5] ]; //Music Instrument
So now if you wanna display some value of 'automobile' for example, just:
//METHOD1
categories['automobile']
//METHOD2
categories[ category[0] ] //category[0]->automobile
And what you get is the array with all the products of category,so you just have to choose wich one you want.
Here you can see what you have got in console.
Function for show it in some HTML ( void html i hope)
function showObjectOnHTML( obj ){
for (var key in categories) { //check categories of thethe object
if (categories.hasOwnProperty(key)) {
var CATEGORIES = key;
var SPAN = document.createElement('SPAN');
SPAN.setAttribute('style','font-weight:bold; font-size: 20px; margin-left: 5px; display:block;');
SPAN.appendChild( document.createTextNode( CATEGORIES ) );
document.body.appendChild(SPAN);
var PRODUCTS = categories[key];
for( var i=0; i<PRODUCTS.length; i++){
var SPAN = document.createElement('SPAN');
SPAN.setAttribute('style','margin-left: 15px;font-size: 20px; display:block;');
SPAN.appendChild( document.createTextNode( PRODUCTS[i] ) );
document.body.appendChild(SPAN);
}
}
}
}
For show it,just type,:
showObjectOnHTML(categories);
I think what you need is an object (used like a "hashmap" in java):
//set examples
var category = {
automobile: [],
fashion: [],
musicInstuments: ["Piano"]
};
category["automobile"] = category["automobile"].concat(["LandRover", "Maserati"]);
category.fashion.push("Vintage");
//get examples
for(var key in category){
category[key].forEach(function(item){
console.log(item);
});
}
console.log(category.automobile[0]);
Using an object will also give you constant access time to the category you are looking for (instead of iterating over n items to find it)
Maybe if you use objects instead of only lists?
var categories = [
{
name: "Automobile",
products: ["LandRover", "Maserati"]
},
{
name: "Fashion",
products: ["Vintage"]
},
{
name: "Music Instruments",
products: ["Guitar", "Drums", "Piano"]
}
]
Also, like someone commented, what exactly do you want to accomplish?
EDIT
This JSFiddle shows one way to list products in each category using AngularJS.

how to create, assign and access new values to object?

How to create, assign and access new values to object ?
Declaring new objects and adding new values to is is problem for me.
can any one help me?
var Countries = [
{
name : 'USA',
states : [
{
name : 'NH',
cities : [
{
name : 'Concord',
population : 12345
},
{
name : "Foo",
population : 456
}
/* etc .. */
]
}
]
},
{
name : 'UK',
states : [ /* etc... */ ]
}
]
Tried like this:
Countries = new Array();
Countries[0] = new Country("USA");
Countries[0].states[0] = new State("NH");
Countries[0].states[0].cities[0] = new city("Concord",12345);
Countries[0].states[0].cities[1] = new city("Foo", 456);
...
Countries[3].states[6].cities[35] = new city("blah", 345);
You're trying to create new objects over and over with things like new Country and new State but you don't have those defined as functions. Something much more simple should work:
Countries[0].states[0].name = "Not New Hampshire";
console.log(Countries[0].states[0].name);
[Edit] : I also highly agree with upsidedown. Please check a tutorial on working with data structures (arrays and objects) in JavaScript.
As #uʍop-ǝpısdn commented, you'll find lots of tutorials.
One of the common pattern for creating "newable" objects in JavaScript goes like this:
var Country = function(name, states){
this.name = name;
this.states = states || [];
}
var State = function(name, cities){
this.name = name;
this.cities = cities || [];
}
var Countries = [];
Countries.push( new Country("USA", [ new State("NH", ...), ... ]) );

creating list of objects in Javascript

Is it possible to do create a list of your own objects in Javascript? This is the type of data I want to store :
Date : 12/1/2011 Reading : 3 ID : 20055
Date : 13/1/2011 Reading : 5 ID : 20053
Date : 14/1/2011 Reading : 6 ID : 45652
var list = [
{ date: '12/1/2011', reading: 3, id: 20055 },
{ date: '13/1/2011', reading: 5, id: 20053 },
{ date: '14/1/2011', reading: 6, id: 45652 }
];
and then access it:
alert(list[1].date);
dynamically build list of objects
var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
listOfObjects.push(singleObj);
});
here's a working example http://jsfiddle.net/b9f6Q/2/
see console for output
Maybe you can create an array like this:
var myList = new Array();
myList.push('Hello');
myList.push('bye');
for (var i = 0; i < myList .length; i ++ ){
window.console.log(myList[i]);
}
Going off of tbradley22's answer, but using .map instead:
var a = ["car", "bike", "scooter"];
a.map(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
return singleObj;
});
Instantiate the array
list = new Array()
push non-undefined value to the list
var text = list.forEach(function(currentValue, currentIndex, listObj) {
if(currentValue.text !== undefined)
{list.push(currentValue.text)}
});
So, I'm used to using
var nameOfList = new List("objectName", "objectName", "objectName")
This is how it works for me but might be different for you, I recommend to watch some Unity Tutorials on the Scripting API.

Categories

Resources