javascript multidimensional objects - javascript

I have the following requirements that needs to be build in javascript objects/array. Can anyone help me with a sample?
Requirements
Start with invoices number. Key: invoice, Value: INV001, INV002, INV003...
Each invoice number contain 1 or more receipt number. 1 receipt number may belongs to 1 or more invoices number. Key: receipt, Value: RCP001, RCP002, RCP003...
Each receipt number contain 1 or more payment method. Key: payment, Value: cash, cc, ibg, chq...
Each payment method contain only 1 amount. Key: amount, Value: 5, 10, 1000, 9999...

JavaScript doesn't inherently support multidimensional arrays.
Instead, You need to create an array of arrays. IE
Start with your 3 primary arrays:
var invoiceArr = ["invoice1", "invoice2", "invoice3"];
var receiptArr = ["receipt1", "receipt2", "receipt3"];
var paymentArr = ["payment1", "payment2", "payment3"];
Add them to a main array:
var mainArray = [invoiceArr, receiptArr, paymentArr];

Are you able to follow the below code or do you need further instructions?
var solution = {
invoice: [{"INV1" : { receipt : ["RCP1" : { payment : ["cash" , "cc"]
} , "RCP2"]
}},
{"INV2" : { receipt : ["RCP1", "RCP2"]
}}
],
}

Related

get a range of numbers from sql column of type varchar

I have a postgres server running with one column (say marks) of type VARCHAR(255), but is supposed to have numbers, like if i do a select *.. query , i will get ['100','50','21','14'...] etc.
i would like to run a range query on it, like user passes [10,30] and gets ['21','14'] as result. I think this would require casting at the time of running the BETWEEN query, but i cannot get it to work properly.
I am using sequalize.js which is generating the following query:
SELECT "id"
FROM "token_attributes" AS "token_attributes"
WHERE "token_attributes"."attributesDirectoryId" = 3
AND CAST('token_attributes.attributeValue' AS INTEGER) BETWEEN 10 AND 30;
on server also this query seems to fail. the sequalize query that is being created is :
{
where: {
attributesDirectoryId: 3,
attributeValue: Where { attribute: [Cast], comparator: '=', logic: [Object] }
},
attributes: [ 'id' ]
}
i have used the following code to create the where condition (cast and where were imported from sequelize):
let whereFilter ={}
let value = where(cast(`${tableName}.attributeValue`, 'integer'), {[Op.between]: rangeAsInt})
whereFilter['attributeValue'] = value
so this is basically calling table.findAll({where:whereFilter}) I am not sure how to either make sequelize create a correct sql api or what the actual correct SQL api would be. can anyone help?
found the issue, i missed the sequilize.col function :
let whereFilter ={}
let value = where(cast(col(`${tableName}.attributeValue`), 'integer'), {[Op.between]: rangeAsInt})
whereFilter['attributeValue'] = value
and the query would be :
SELECT "id"
FROM "token_attributes" AS "token_attributes"
WHERE "token_attributes"."attributesDirectoryId" = 3
AND CAST("token_attributes"."attributeValue" AS INTEGER) BETWEEN 10 AND 30;

Return json array if matches input

Need help:
I have my JSON formatted array. What I can't seem to wrap my head around is how to all the contents of said array when it matches user input. I can display the whole array and i can check if the input is in the array.
Code:
//user input
var product = document.getElementById('product').value;
var price = document.getElementById('price').value;
var quantity = document.getElementById('quantity').value;
//Products
var viewInventory = [{
id : 'a',
name : 'iphone',
model : 10,
price : 900,
quantity : 25
}, {
id: 'b',
name : 'pixel',
model : 1,
price : 800,
quantity : 40
},{
id: 'c',
name : 'pants',
model : 8,
price : 700,
quantity : 80
},{
id: 'd',
name : 'essential',
model : 10,
price : 900,
quantity : 25
}];//end of viewInventory
console.log(viewInventory);//just testing to see it JSON obj works
function hello(){
var item;
for (var i = 0; item = viewInventory[i].name; i++){
console.log(item);
// console.log(viewInventory[i].name)
if (product === item){
console.log(viewInventory[i]);
console.log(item + "This is input");
// document.write(myTable);
}
}
Problem:
Below is the problem from my book ( i am self learning).
Pulling data from a file into a complex data structure makes parsing much simpler. Many programming languages support the JSON format, a popular way of representing data.
Create a program that takes a product name as input and retrieves the current price and quantity for that product.The product data is in a data file in the JSON format and looks like this:
{
_"products" : [
_{"name": "Widget", "price" : 25.00, "quantity": 5 },
__{"name": "Thing", "price": 15.00, "quantity": 5},
__{"name": "Doodad", "price": 5.00, "quantity": 10}
__]
}
Print out the product name, price, and quantity if the product is found. If no product matches the search, state, that no product was found and start over.
Example output
What is the product name? iPad
Sorry, that product was not found in our inventory
What is the product name? Widget
Name: Widget
Price: $25.00
Quantity on hand: 5
Constraints
The file is in the JSON format. Use a JSON parser to pull the values out of the file.
If no record is found, prompt again.
Challenges
Ensure that the product search is case-insensitive.
When a product is not found, ask if the product should be added. If yes, ask for the price and the quantity, and save it in the JSON file. Ensure the newly added product is immediately available for searching without restarting the program.
you can use the Array.prototype.filter function:
var product = document.getElementById('product').value;
var price = document.getElementById('price').value;
var quantity = document.getElementById('quantity').value;
var matchingProducts = viewInventory.filter((v)=>v.name.indexOf(product)>-1);
if(!matchingProducts.length) alert('Sorry, that product was not found in our inventory');
else {
alert(
matchingProducts.reduce(
(c,i)=>c+i.name+' found with price='+i.price+' and the quantity='+i.quantity+'\n',
''
)
);
}

Google Apps Script: how to copy array of objects to range?

I have an array of objects called membership:
[{name: 'Linus Pauling', address: '1805 Main Street', phone: '(615) 555-1010',
email: 'linus.pauling#gmail.com' },
{name: 'Maury Povich', address: '382 North Street', phone: '(423) 555-1997',
email: 'maury#themauryshow.org'}]
(Although only 4 are shown here, I really have ten key/value pairs per member.)
What is the best way to copy bits of this array to a range of cells in Google Sheets? I am trying to find a method to call the object values directly, and use the .SetValues method to copy them en masse, as opposed to one at a time.
To get all the members' names in column A, I've tried:
sheet.getRange(1,1,membership.length,1).setValues(membership[{member.name}]);
...which gives Missing : after property ID.
Or:
sheet.getRange(1,1,membership.length,1).setValues([membership[name]]);
...which gives ReferenceError: "name" is not defined.
Or:
sheet.getRange(1,1,membership.length,1).setValues([member.name]);
...which gives the "Cannot convert Array to Object[][]" error.
I apologize for the newbie question. I have seen answers about how to copy values from a multidimensional array to a sheet's range, but not an array of objects.
Are you looking to produce a table in the form:
name | Address | phone | email
-----+---------+-------+------
.... | .... | .... | ....
etc?
If so, then the following snippet may help. The key thing to point out here is that you can't expect a given order when iterating through an object. i.e. Just because your representation of membership lists name first, doesn't mean that if you were to use a for ... in loop you could guarantee that name would come back first - Objects in JavaScript are unordered.
To ensure a given order, the snippet I list defines an array headings in which you specify the order of the columns you want in the Sheet. This is used to guarantee the column order in the output:
var membership = [
{
name: 'Linus Pauling', address: '1805 Main Street', phone: '(615) 555-1010',
email: 'linus.pauling#gmail.com'
},
{
name: 'Maury Povich', address: '382 North Street', phone: '(423) 555-1997',
email: 'maury#themauryshow.org'
}
];
// Headings in the column order that you wish the table to appear.
var headings = ['name', 'address', 'phone', 'email'];
var outputRows = [];
// Loop through each member
membership.forEach(function(member) {
// Add a new row to the output mapping each header to the corresponding member value.
outputRows.push(headings.map(function(heading) {
return member[heading] || '';
}));
});
// Write to sheets
if (outputRows.length) {
// Add the headings - delete this next line if headings not required
outputRows.unshift(headings);
SpreadsheetApp.getActiveSheet().getRange(1, 1, outputRows.length, outputRows[0].length).setValues(outputRows);
}
Output is :
How about following script? This script is a container bound script of spreadsheet. There are 2 patterns. The arrangement of data is different for between pattern 1 and 2.
Pattern 1 is
Pattern 2 is
function main() {
var data = [{name: 'Linus Pauling', address: '1805 Main Street', phone: '(615) 555-1010',
email: 'linus.pauling#gmail.com' }, {name: 'Maury Povich', address: '382 North Street', phone: '(423) 555-1997',
email: 'maury#themauryshow.org'}];
var sheet = SpreadsheetApp.getActiveSheet();
var result = pattern1(data);
var result = pattern2(data);
sheet.getRange('a1').offset(0, 0, result.length, result[0].length).setValues(result);
}
function pattern1(data){
var ar = [];
for (var i in data){
for (var key in data[i]){
ar.push([key, data[i][key]]);
}
}
return ar;
}
function pattern2(data){
var ar = [];
var keys = [];
var values = [];
for (var i in data){
for (var key in data[i]){
if (i == 0) keys.push(key);
values.push(data[i][key]);
}
if (i == 0){
ar.push(keys);
keys = [];
}
ar.push(values);
values = [];
}
return ar;
}
If my understanding for your questions was wrong, I apologize.
See the script at the bottom of the Simple Mail Merge Tutorial for some useful code to retrieve data. Copy all the code from this comment down:
//////////////////////////////////////////////////////////////////////////////////////////
//
// The code below is reused from the 'Reading Spreadsheet data using JavaScript Objects'
// tutorial.
//
/////////
/////////////////////////////////////////////////////////////////////////////////
// getRowsData iterates row by row in the input range and returns an array of objects.
Once you have, the getRowsData returns not only the data, but a second item which is a list of the Headers. Using this, you can modfy the code from #Bardy to allow for the Headers in any order, and also other possible columns in between.

Fuzzy string match + amount match in node.js

Hi i need to order the data according to the fuzzy matching of 2 variables
Consider i have a string :"pet" and Amount 50
I have an object array as like below:
[{"des":"permanent","amount":100}, {"des":"petrol","amount":1000}]
I need an array as below
[{"des":"petrol","amount":100}, {"des":"permanent","amount":1000}] if suppose petrol is highest matching also its nearer to the value 50.
I used fuzzy npm package as follows:
var options = {
extract: function(el) { return el.description; }
};
var results = fuzzy.filter(description, res, options);
But here i can check for only string, but how can i do also for amount?? Thanks in advance
Your specification isn't entirely clear, but it seems like you want sorting (changing the order of elements based on some critieria) rather than filtering (removing elements based on some criteria).
There are two possibilities:
You want to sort by fuzzy score on the des string value, then break ties by the amount proximity.
You want to sort by some aggregate weight between the fuzzy des score and by the amount proximity.
Here's the first option:
const search = {des: "pet", amount: 10};
const data = [
{des: "pet", amount: 1000},
{des: "petrol", amount: 38},
{des: "petrol", amount: -17},
{des: "pets", amount: 9},
{des: "pet", amount: 999},
];
data.sort((a, b) => {
const {score: desA} = fuzzy.match(search.des, a.des);
const {score: desB} = fuzzy.match(search.des, b.des);
if (desA !== desB) {
return desB - desA;
}
return Math.abs(search.amount - a.amount) -
Math.abs(search.amount - b.amount);
});
console.log(data);
<script src="https://unpkg.com/fuzzy#0.1.3/lib/fuzzy.js"></script>
The second option is more involved, so I'll describe it on a high level. Use fuzzy.match to figure out the score for each des string, figure out how close amount is to the search target, normalize these to the same scale (probably 0 through 1), then weigh the scores by some amount to give a final score. Sort on the final score for each element.
Be careful: fuzzy.match().score returns Infinity for perfect matches, so you might want to convert that to 0 for certain operations.

ExtJS 4 group by one column in store, total another

I have a store of data representing bank deposits. The data looks something like this:
{ account : 'a', amount : 5 },
{ account : 'a', amount : 15 },
{ account : 'b', amount : 7 },
{ account : 'b', amount : 3 },
{ account : 'c', amount : 12 },
I would like to display this data in a grid that groups by account and totals amount. I do not want to display the original data. Just the grouped data.
Account Total Amount
a 20
b 10
c 12
If this were a sql database the query would be along these lines:
select account, sum( amount ) from tbl group by account;
is this possible in extjs without doing it manually? I cannot seem to get it to work.
I have called this method on my store:
store.group('account');
And my column in my grid panel that should display the total looks like this:
{
:text => 'Total Amount',
:dataIndex => 'amount',
:summaryType => 'sum',
},
I know the group is doing something because I can change the order from ASC to DESC and the grid displays it differently. But for now the grid just displays all of the rows with no grouping.
Thanks for the help.
I am afraid that Ext JS doesn't have support for displaying data exactly as you want.
You can use Ext.grid.feature.GroupingSummary feature
documentation: http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.grid.feature.GroupingSummary
Or you can get grouped data from grouped store by
store.getGroups()
and process them manually.
documentation: http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.Store-method-getGroups

Categories

Resources