Javascript seperate value from array - node.js

I have this,
[{"cart_id":"5BqDu","product":[{"id":1,"qty":"11","name":"test product","pv":"100","price":"23","sub_price":253,"sub_pv":1100},{"id":2,"qty":"11","name":"test product 2","pv":"null","price":"11","sub_price":121,"sub_pv":null}],"shipping":{"member_id":"00000000","member_pass":"0987654321","receiver":"asasdsdasd123","full_address":"Taman ABC Lorong ccc Bagan Gajar, 11100 Pulau pINANG.","postcode":"21313213","country":"malaysia","phone_no":"321312"}},{"cart_id":"xEopa","product":[{"id":2,"qty":"1","name":"test product 2","pv":"null","price":"11","sub_price":11,"sub_pv":null}],"shipping":{"member_id":"09876543","member_pass":"11232312","receiver":"sdasdsadas","full_address":"adsadzcfdhg43324","postcode":"12323","country":"malaysia","phone_no":"321312"}},{"cart_id":"0WyEm","product":[{"id":2,"qty":"5","name":"test product 2","pv":"null","price":"11","sub_price":55,"sub_pv":null},{"id":1,"qty":"3","name":"test product","pv":"100","price":"23","sub_price":69,"sub_pv":300}],"shipping":{"member_id":"12345678","member_pass":"0987654321","receiver":"MR ABCDEF","full_address":"NO. 123, LORONG ABC, TAMAN AMAN CCC, BAGAN AJAM, 11100 KUALA LUMPUR, MALAYSIA.","postcode":"123453","country":"MALAYSIA","phone_no":"0123456789"}},{"cart_id":"ox9IK","product":[{"id":1,"qty":"2","name":"test product","pv":"100","price":"23","sub_price":46,"sub_pv":200},{"id":2,"qty":"5","name":"test product 2","pv":"null","price":"11","sub_price":55,"sub_pv":null}],"shipping":""},{"cart_id":"jz2j2","product":[{"id":1,"qty":"1","name":"test product","pv":"100","price":"23","sub_price":23,"sub_pv":100},{"id":2,"qty":"4","name":"test product 2","pv":"null","price":"11","sub_price":44,"sub_pv":null}],"shipping":""},{"cart_id":"6eE0x","product":[{"id":1,"qty":"1","name":"test product","pv":"100","price":"23","sub_price":23,"sub_pv":100}],"shipping":{"member_id":"S4567890","member_pass":"atomy123","receiver":"Siew","full_address":"56, Jalan Emas 8, Taman Bukit Beruang.","postcode":"75750","country":"Malaysia","phone_no":"0198907654"}},{"cart_id":"iRw6b","product":[{"id":2,"qty":"1","name":"test product 2","pv":"null","price":"11","sub_price":11,"sub_pv":null}],"shipping":{"member_id":"12345670","member_pass":"121334","receiver":"sdfsdaf","full_address":"sgdfgdfs","postcode":"12341","country":"Malaysia","phone_no":"0192321008"}},{"cart_id":"bbKf9","product":[{"id":2,"qty":"1","name":"test product 2","pv":"null","price":"11","sub_price":11,"sub_pv":null}],"shipping":{"member_id":"S6789212","member_pass":"12345678","receiver":"Mary","full_address":"Taman Tasik Utama","postcode":"12233","country":"Malaysia","phone_no":"0197321830"}},{"cart_id":"B1DLq","product":[{"id":2,"qty":"5","name":"test product 2","pv":"null","price":"11","sub_price":55,"sub_pv":null},{"id":1,"qty":"1","name":"test product","pv":"100","price":"23","sub_price":23,"sub_pv":100}],"shipping":{"member_id":"09876556","member_pass":"hijk","receiver":"sim","full_address":"Taman Tasik Utama","postcode":"12233","country":"Malaysia","phone_no":"0987654321"}}]
I only need product id from all
What can I do ?

Try this:
let carts = / * the data you posted above */
let ids = [];
carts.forEach(cart => {
const products = cart.product;
products.forEach(product => {
ids.push(product.id);
});
});
Note that there are no check that handles a missing if property so you might want to add that.

Related

Array list with 2 values and doing it to a top 10 list

im working on a Discord bot and have a reputation system with fs (npm package) and saving peoples reps in a file and doing the file name as they discord id
now im working on a top 10 command and would need some help here, i currently have this as code:
let users = [];
let reps = [];
fs.readdirSync('./data/reps/').forEach(obj => {
users.push(obj.replace('.json', ''))
let file = fs.readFileSync(`./data/reps/${obj}`)
let data = JSON.parse(file)
reps.push(data.reps)
})
let top = [...users, ...reps]
top.sort((a,b) => {a - b})
console.log(top)
the files form the users are like this:
{
"users": [
"437762415275278337"
],
"reps": 1
}
users are the current users that can't rep the persion anymore and don't need to use it in the command
i wan to get the top 10 of reps so that i can get the user id and how many reps they have, how could i do it with the code above?
You could try this
const topTen = fs.readdirSync('./data/reps/').map(obj => {
const file = fs.readFileSync(`./data/reps/${obj}`);
const data = JSON.parse(file);
return { ...data, name: obj.replace('.json', '') };
}).sort((a, b) => a.reps - b.reps).slice(0, 10);
console.log(topTen);
I would change how you push the data
const users = [];
fs.readdirSync('./data/reps/').forEach(obj => {
let file = fs.readFileSync(`./data/reps/${obj}`)
let data = JSON.parse(file)
reps.push({ reps: data.reps, id: obj.replace(".json", "") });
})
That way when you sort the array the id goes along with
//define this after the fs.readdirSync.forEach method
const top = users.sort((a,b)=> a.reps-b.reps).slice(0,10);
If you want an array of top ids
const topIds = top.map(e => e.id);
If you want a quick string of it:
const str = top.map(e => `${e.id}: ${e.reps}`).join("\n");
Also you should probably just have one or two json files, one would be the array of user id's and their reps and then the other could be of user id's and who they can't rep anymore

Hyperledger Composer - ACL Rule with function in condition

I'm trying to write a little complexer logic in the condition of an ACL Rule as always the p.getIdentifier() == r.getIdentifier(), because in my fault it isn't possible.
These are my models:
participant Customer identified by customerID {
o String customerID
o String name
...
}
asset A identified by aID {
o String aID
--> Customer customer
}
asset B identified by bID {
o String bID
--> A a
}
Now I want to give the Customer access to see all B assets, but only where the relationship to A references to an asset, which have a relatinship to the actual participant of Customer, who is "logged in".
Summarized logic: From asset B to A, and then from A to Customer.
So in this case I can't compare the identifiers of Customer and B directly and have to go over A. Therefore I wanted to evaulate the access with a function which is called in the script.js file:
rule CustomerAccessCustomer {
description: "The customer should see all B assets, but only when he have a relationship in asset A "
participant(p): "org.xxx.test.participant.Customer"
operation: READ
resource(r): "org.xxx.test.asset.B"
condition: (evaluateAccess(p,r))
action: ALLOW
}
Here is the function of the script.js:
async function evaluateAccess(p,r) {
try {
const bRegistry = await getAssetRegistry('org.xxx.test.asset.B');
const b = await bRegistry.get(r.getIdentifier());
const aRegistry = await getAssetRegistry('org.xxx.test.asset.A');
const a = await aRegistry.get(b.a.getIdentifier());
if (p.getIdentifier() === a.customer.getIdentifier()) {
return true;
}
} catch (error) {
console.log(error);
}
}
But I get an error Error: The runtime API is not available.
Do I think the wrong way, isn't it possible to evaluate access with a function?
How did you handle access rule if you can't just compare the identifiers?
you should just be able to do:
rule CustomerAccessCustomer {
description: "The customer should see all B assets, but only when he have a relationship in asset A "
participant(p): "org.xxx.test.participant.Customer"
operation: READ
resource(r): "org.xxx.test.asset.B"
condition: ( (p.getIdentifier() === r.a.customer.getIdentifier())
action: ALLOW
}
but p would also need READ access already to be able to 'read' Asset resource 'A' (to check the identifier etc) in the first place :-)
The customer should be participant not asset:
participant Customer identified by customerID {
o String customerID
o String name
}

Relate/link vendor bill to purchase order in Netsuite

I have created vendor bill with nlapiCreateRecord, I can see the Bill record in the system with all items I want, but I can't relate it / link it to specific Purchase Order natively. When I'm using nlapiTransformRecord I'm deleting all records first from the PO and I'm adding new line items from CSV, but the native link/relationship between PO and Vendor Bill is missing. Here is my code created for the Bill Import from CSV:
function BillImport() {
var fromrecord;
var fromid;
var torecord;
var record;
var qty;
fromrecord = 'purchaseorder';
fromid = 23664;
torecord = 'vendorbill';
var loadedBillFile = nlapiLoadFile(5034);
var loadedBillString = loadedBillFile.getValue();
var BillLines = loadedBillString.split('\r\n'); //split on newlines
record = nlapiTransformRecord(fromrecord, fromid, torecord);
//trecord.setFieldValue('location', 1);
//trecord.setFieldValue('tranid', 'TEST!');
//var record = nlapiCreateRecord('vendorbill');
for (var j = record.getLineItemCount('item'); j>=1; j--)
{
record.removeLineItem('item',j);
}
for (var i = 1; i < BillLines.length; i++) {
var cols = BillLines[i].split(';');
var dsplit = cols[4].split(".");
var date = new Date(dsplit[2],dsplit[1],dsplit[0]);
currentDate = date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear();
var entity = cols[0]; // OK HEAD
var currency = cols[1]; // OK LINE
var taxcode = cols[2]; // SKIP
var tranid = cols[3]; // OK HEAD
var trandate = currentDate; // OK HEAD FORMAT 11/3/2016
var location = 21;//cols[5]; // OK HEAD (ID of Location)
var item = cols[6]; // OK LINE
var quantity = cols[7];
var rate = parseFloat(cols[8]); // FLOAT
var amount = parseFloat(cols[9]);
var po = cols[10];
record.selectNewLineItem('item');
// Head Level
record.setFieldValue('createdfromstatus','');
record.setFieldValue('entity', entity);
record.setFieldValue('tranid', tranid);
record.setFieldValue('trandate', trandate);
record.setFieldValue('location', location);
// Line Level
record.setCurrentLineItemValue('item','item', item);
record.setCurrentLineItemValue('item','quantity', quantity);
record.setCurrentLineItemValue('item','rate', rate);
record.setCurrentLineItemValue('item','amount', amount);
//record.setCurrentLineItemValue('item','orderdoc', po);
//record.setCurrentLineItemValue('item','podocnum', po);
record.commitLineItem('item');
}
var id = nlapiSubmitRecord(record, true);
//trecord.setLineItemValue('item', 'amount', 1, 3 );
//var idl = nlapiSubmitRecord(trecord, true);
}
Here is the example CSV file:
Entity;Currency;Taxcode;Tranid;TranDate;Location;Item;Quantity;Rate;Amount;PO Internal ID
2449;USD;0.00 ;224676;11.3.2016;21;885;1;10;50;23664
2449;USD;0.00 ;224676;11.3.2016;21;870;2;10;120;23664
2449;USD;0.00 ;224676;11.3.2016;21;890;3;3;45;23664
2449;USD;0.00 ;224676;11.3.2016;21;948;4;4,66;38,5;23664
2449;USD;0.00 ;224676;11.3.2016;21;886;5;19,54;720;23664
I'm
If you don't want it to transform into a Vendor Bill (probably to avoid the PO from changing status) then you will need to create a custom relationship. You do this by:
Create a custom field on the Vendor Bill form of type "List/Record" and have the it be of "Transaction" type and check "Record is Parent". Save the Custom Field.
Go back to the custom field and edit it. Go to the display tab and select a "Parent Subtab", I usually select "Related Records". Save.
Now you just need to create a new Vendor Bill from scratch and save the record id of the PO in the Vendor Bill using the new custom field. Leave the "Created From" field blank, otherwise you would be linking them natively. The Bill should be listed under the "Related Records" tab or whichever subtab you selected on the PO.
Vendor bill import via CSV method is doable but you can bill the Purchase Order completely and not partially i.e. if you try to import a bill mentioning any referenced Purchase Order's link in it, it'll create a bill for all the remaining unbilled quantities of the Purchase Order rather than the quantity you have mentioned.
Actually if you mention any quantity AND Purchase Order link BOTH in the CSV file then it will throw an error.
Below is the part I found from the SuiteAnswers with answer id as 10020.
Refer the supporting image here

Randomize loading order of products

I am working on a site for a friend which is a site where she can sell her goods. I got the index view loading with the help of EF 6, MVC 5 and some people on here. Now I was wondering if there was a way to randomize the loading order so it's different each time. Here's is the code for the products control index method:
private AccessorizeForLessEntities entities = new AccessorizeForLessEntities();
// GET: /Products/
public ActionResult Index()
{
var products = entities.Products.Include(p => p.ProductImage);
IEnumerable<DisplayProductsViewModel> model = products.Select(p => new DisplayProductsViewModel()
{
Id = p.ProductId,
Name = p.ProductName,
Image = p.ProductImage,
Price = p.ProductPrice.ToString()
}).ToList();
return View(model);
}
Is there a way I can alter this code to randomize the loading order?
Just order by something random. For example:
entities.Products.Include(p => p.ProductImage).OrderBy(o => Guid.NewGuid())

How to set conditions/filters on references when using Load* methods

I have two tables: Customer and Orders. The customer has a reference to Orders like such:
[Reference]
public List<Order> Orders { get; set; }
The Order class has an attribute Deleted. I'd like to load all Customers (or a subset), and include the Orders, but not the ones with Deleted=true. Can this be done with LoadSelect methods, or what is the recommended way?
Something that would roughly equal the following SQL:
select * from Customers C
join Orders O on O.CustomerId = C.Id
where O.Deleted = False
Is this the best way?
var orderIds = resp.Customers.Select(q => q.Id).ToList();
var allOrders = Db.Select<Order>(o => orderIds.Contains(o.CustomerId) && !o.Deleted);
foreach (var order in allOrders)
{
var cust = resp.Customers.First(q => q.Id == order.custivityId);
if (cust.Orders == null) cust.Orders = new List<Order>();
cust.Orders.Add(order);
}
I've just added a new Merge API in this commit to automatically join a parent collection with their child references that will make this a little easier.
With the new API you can select customers and orders separately and merge the collections together, e.g:
//Select only Customers which have valid orders
var customers = db.Select<Customer>(q =>
q.Join<Order>()
.Where<Order>(o => o.Deleted == false)
.SelectDistinct());
//Select valid orders
var orders = db.Select<Order>(o => o.Deleted == false);
customers.Merge(orders); //merge the results together
customers.PrintDump(); //print the results of the merged collection
This change is available from v4.0.39+ that's now available on MyGet.

Resources