i have problem when im using array into my render apps..
here my code for getting list chat from sqlite..
return new Promise(resolve => {
const listchat = [];
this.initDB()
.then(db => {
db.transaction(tx => {
tx.executeSql(
'SELECT num, text, type, _id,user FROM chat where CAST(user as INT) order by num desc',
[],
).then(([tx, results]) => {
var len = results.rows.length;
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
var user = {id: 2, avatar: null};
const {num, text, type, _id} = row;
listchat.push({
num,
text,
type,
_id,
user,
});
}
resolve(listchat);
});
})
.then(result => {
this.closeDatabase(db);
})
.catch(err => {
console.log(err);
});
})
});
and i got results from query like this :
[
{
"_id": "6d357f55-5fb8-4fec-ac5f-26cc1df4b98d",
"num": 1,
"text": "here must number 111111111111111111",
"type": null,
"user": {
"avatar": null,
"_id": 2
}
}
]
and what i need is no quotes on "avatar and id"
[
{
"_id": "6d357f55-5fb8-4fec-ac5f-26cc1df4b98d",
"num": 1,
"text": "here must number 111111111111111111",
"type": null,
"user": {
avatar: null,
_id: 2
}
}
]
the problem is on quotes.. someone have solution for this ?
Related
My function further below seems fine yet the count is overstated in some instances, eg: should count '1' but shows '2'.
Data source for context:
{
"currency": "USD",
"services": [
{
"category": [
{"token": "token1"},
{"token": "token2"}
],
"price": 149
},
{
"category": [
{"token": "token3"},
{"token": "token4"}
],
"price": 149
}
]
},
{
"currency": "EUR",
"services": [
{
"category": [
{"token": "token1"},
{"token": "token2"}
],
"price": 149
},
{
"category": [
{"token": "token3"},
{"token": "token4"}
],
"price": 149
}
Goal: COUNT the frequency of category tokens per price, sorted by currency in their own objects.
Desired output schema (for illustration purposes, unrelated to above schema example):
{
"result": [
{
"currency": "USD",
"token": "Wellness",
"count": 1,
"price": 100
},
{
"currency": "USD",
"token": "Adventure",
"count": 1,
"price": 300
}
]
}
It appears that sometimes, the count is not right, by +1 or +2 difference for no apparent reasons.
My function, which outputs wrong counts:
const data = inputs.data;
const result = [];
let error = null;
try {
data.forEach(item => {
item.services.forEach(service => {
service.category.forEach(tokenObject => {
const token = tokenObject.token;
const existingToken = result.find(item => item.token === token && item.price === service.price && item.currency === item.currency);
if (existingToken) {
existingToken.count++;
} else {
result.push({currency: item.currency, token, count: 1, price: service.price});
}
});
});
});
} catch (e) {
error = "error";
}
return error ? [1, {error}] : [0, {result}]
Any way to make it "fool-proof" with some kind of "UNIQUE" safe guard?
Note: I'm beginner in JS.
I've used OpenAI's playground and it gave me the right function!
It suggested to "modify the existing code to use a Map data structure instead of an array to store the token count information. The Map will allow to keep track of each token, currency, and price combination as a key, and its count as the value"
const data = inputs.data;
const result = [];
let error = null;
try {
const tokenMap = new Map();
data.forEach(item => {
item.services.forEach(service => {
service.category.forEach(tokenObject => {
const token = tokenObject.token;
const key = `${token}-${service.price}-${item.currency}`;
if (tokenMap.has(key)) {
tokenMap.set(key, tokenMap.get(key) + 1);
} else {
tokenMap.set(key, 1);
}
});
});
});
tokenMap.forEach((count, key) => {
const [token, price, currency] = key.split('-');
result.push({currency, token, count, price: Number(price)});
});
} catch (e) {
error = "error";
}
return error ? [1, {error}] : [0, {result}]
how to walk through the entire array (we have the form of a tree) and wait for the result?
there is an array
arr=[ {
"id": ,
"name": "",
"url": "",
"childs": [
{
"id": ,
"parent": ,
"name": "",
"url": "",
"childs":[{}{}],
},
{
"id": ,
"parent": ,
"name": "",
"url": "",}]
an element can have child elements, and they still have children.
for (const cat of arr) {
if (cat['childs']) {
for (const child of cat['childs']) {
if (!child['childs']) {
const category_name = child['name'];
const category_url = child['url'];
categoryes.push({
category_name: category_name,
category_url: category_url,
});
} else {
for (const sub_child of child['childs']) {
if (!sub_child['childs']) {
const category_name = sub_child['name'];
const category_url = sub_child['url'];
const shard = sub_child['shard'];
const query = sub_child['query'];
categoryes.push({
category_name: category_name,
category_url: category_url,
});
} else {
for (const sub_child2 of sub_child['childs']) {
if (!sub_child2['childs']) {
const category_name = sub_child2['name'];
const category_url = sub_child2['url'];
categoryes.push({
category_name: category_name,
category_url: category_url,
});
} else {
for (const sub_child3 of sub_child2['childs']) {
console.log(sub_child3);
if (sub_child3['childs']) {
console.log(sub_child3);
}
}
}
}
}
}
}
}
}
}
but I do not know how many nested elements there can be. How to go through all and wait for the result?
using recursion like this might help you :-
let categoryes = [];
function walkEntireArray(arr){
arr.forEach(element => {
if(typeof element["childs"] !== 'undefined') {
walkEntireArray(childs)
}
const category_name = element['name'];
const category_url = element['url'];
categoryes.push({
category_name: category_name,
category_url: category_url,
});
});
}
I am trying to move everything in the Array Results outside and into the original object
this is the object
{
"Name": "John",
"Results": [
{
"Type": "DB",
"Immediate_Action": "No",
}
]
}
It should look like this
{
"Name": "John",
"Type": "DB",
"Immediate_Action": "No",
}
What I have so far is this
const mapOscarResults = ({ data }) => {
return data.map(entry => {
let mapped = {...entry};
entry.Results.forEach(key => {
let Type = mapped[key.Type]
if (mapped[key]) {
mapped[key].push(entry.Results[key]);
} else {
mapped[key] = [entry.Results[key]];
}
});
return mapped;
});
};
You can simply spread the Results array into an Object.assign() call.
const input = { "Name": "John", "Results": [{ "Type": "DB", "Immediate_Action": "No", }, { "Another": "value" }] };
const { Results, ...refactored } = input;
Object.assign(refactored, ...Results);
console.log(refactored)
This code works for your example:
const { Results: results, ...rest } = {
"Name": "John",
"Results": [
{
"Type": "DB",
"Immediate_Action": "No",
}
]
}
const res = {...rest, ...results.reduce((prev, curr) => ({
...prev,
...curr
}), {})}
console.log(res)
But I don't know what you expect when the Results array has more than one element.
In that condition, if this code does not fill your needs, ask me to change it.
however, it will join first Result with index 0, you can expand it
const data = {
"Name": "John",
"Results": [
{
"Type": "DB",
"Immediate_Action": "No",
}
]
}
const mapOscarResults = (data) => {
for (let i in Object.keys(data)){
if (Array.isArray(data[Object.keys(data)[i]])){
newKey = data[Object.keys(data)[i]][0]
data = {... data, ...newKey}
delete data[Object.keys(data)[i]]
}
}
return data
};
console.log(mapOscarResults(data))
I have a json-server with the following files:
db.json:
var faker = require('faker');
module.exports = function () {
var data = {
slack_users_list: slack_users_list(),
slack_users_info: slack_users_info()
}
return data;
}
function slack_users_list() {
const data = {
members: []
}
for (var i = 0; i < 10; i++) {
data.members.push({
id: "user_id_" + i
})
}
return data;
}
function slack_users_info() {
const data = {
user: []
}
for (var i = 0; i < 10; i++) {
data.user.push({
id: "user_id_" + i,
name: faker.internet.userName(),
team_id: faker.datatype.string(),
profile: {
title: faker.name.title(),
first_name: faker.name.firstName(),
last_name: faker.name.lastName(),
title: faker.name.title(),
email: faker.internet.email(),
phone: faker.phone.phoneNumber(),
skype: faker.internet.userName(),
},
})
}
return data;
}
And server.js:
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router(require('./db.js')())
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)
// Wrap response depending on the object being called.
router.render = (req, res) => {
if (req.url.startsWith('/slack_users_list')) {
res.jsonp(res.locals.data)
} else if (req.url.startsWith('/slack_users_info')) {
param_user = req.query.user
if (param_user == null) {
res.jsonp({
"ok": false,
"error": "user_not_found"
})
return
}
user_list = res.locals.data.user
user_info = {}
for (var i = 0; i < user_list.length; i++) {
if (user_list[i].id == param_user) {
user_info = user_list[i]
}
}
res.jsonp({ user: user_info })
} else {
res.jsonp(res.locals.data)
}
}
server.use(router)
// Run server on indicated port.
server.listen(port = 3000, () => {
console.log('JSON Server is running')
console.log('http://localhost:' + port)
})
So when I call http://localhost:3000/slack_users_list I get:
{
"members": [
{
"id": "user_id_0"
},
{
"id": "user_id_1"
},
{
"id": "user_id_2"
},
{
"id": "user_id_3"
},
{
"id": "user_id_4"
},
{
"id": "user_id_5"
},
{
"id": "user_id_6"
},
{
"id": "user_id_7"
},
{
"id": "user_id_8"
},
{
"id": "user_id_9"
}
]
}
But if I want to apply pagination to it (e.g. http://localhost:3000/slack_users_list?_page=1&_limit=2), I get all the same objects, I assume because the pagination is getting applied to the first line of objects and not to each of the element inside members that get generated in db.json.
How can I modify this to apply the pagination on the sub-object members?
Thanks!
You can do the pagination right before sending the response.
// !!!
// This is just for demonstration.
// consider this req as the actual request.(req, res)
const req = {
params: { _page: '2', _limit:'3'}
}
// consider this as actual slack_users_list.members
const members = [
{
"id": "user_id_0"
},
{
"id": "user_id_1"
},
{
"id": "user_id_2"
},
{
"id": "user_id_3"
},
{
"id": "user_id_4"
},
{
"id": "user_id_5"
},
{
"id": "user_id_6"
},
{
"id": "user_id_7"
},
{
"id": "user_id_8"
},
{
"id": "user_id_9"
}
]
const page=Number(req.params._page)
const limit=Number(req.params._limit)
// paginating
const limited = members.slice((page - 1) * limit, page * limit)
console.log(limited)
// // send paginated response
//res.json(limited)
In grouped result I need the property of vendor and store in new array. but the give me some error. the error is Error: words is not defined.
how can I get vendor property from grouped list?
it is about to get result and store in new property.
const cart = {
"_id": 2,
"owner": 7,
"products": [{
"_id": {
"$oid": "5f06f9a4b8b878050fbc54b2"
},
"product": 1,
"vendor": 1,
"quantity": 2
}, {
"_id": {
"$oid": "5f06f9a4b8b878050fbc54b3"
},
"product": 2,
"vendor": 1,
"quantity": 1
}, {
"_id": {
"$oid": "5f06f9a4b8b878050fbc54b4"
},
"product": 4,
"vendor": 2,
"quantity": 1
}],
"createdAt": {
"$date": "2020-06-21T06:46:40.111Z"
},
"updatedAt": {
"$date": "2020-07-09T11:04:04.459Z"
},
"__v": 0,
"totalPrice": 265
}
const product = cart.products;
var grouped = product.reduce((dictionary, p) => {
dictionary[p.vendor] = dictionary[p.vendor] || [];
dictionary[p.vendor].push(p);
return dictionary;
}, {})
for (const p in grouped) {
console.log(grouped[p].vendor)
}
const cart = {
_id: 2,
owner: 7,
products: [
{
_id: {
$oid: "5f06f9a4b8b878050fbc54b2",
},
product: 1,
vendor: 1,
quantity: 2,
},
{
_id: {
$oid: "5f06f9a4b8b878050fbc54b3",
},
product: 2,
vendor: 1,
quantity: 1,
},
{
_id: {
$oid: "5f06f9a4b8b878050fbc54b4",
},
product: 4,
vendor: 2,
quantity: 1,
},
],
createdAt: {
$date: "2020-06-21T06:46:40.111Z",
},
updatedAt: {
$date: "2020-07-09T11:04:04.459Z",
},
__v: 0,
totalPrice: 265,
};
// const result = words.filter((word) => word.length > 6); // useless line, you do not have variable 'words'
const f = cart.products.filter((p) => p.vendor == 1);
const products = cart.products; //better variable naming
var grouped = products.reduce((dictionary, p) => {
dictionary[p.vendor] = dictionary[p.vendor] || [];
dictionary[p.vendor].push(p);
return dictionary;
}, {});
for (const p in grouped) {
console.log(grouped[p]); //is array
}
To fix this code just delete the line where you use variable words coz you didn't declare such.
To get vendor value:
grouped[p] is an array. It doesn't have a property vendor. But you can get it with:
for (const p in grouped) {
console.log(grouped[p][0].vendor);
}
or get an array of them:
let vendors = Object.getOwnPropertyNames(grouped);
Aside from the 2 lines of code which do nothing, I think you're trying to get the id of the vendor for each group - in which case this is just p in your code at the bottom which logs:
const cart = {"_id":2,"owner":7,"products":[{"_id":{"$oid":"5f06f9a4b8b878050fbc54b2"},"product":1,"vendor":1,"quantity":2},{"_id":{"$oid":"5f06f9a4b8b878050fbc54b3"},"product":2,"vendor":1,"quantity":1},{"_id":{"$oid":"5f06f9a4b8b878050fbc54b4"},"product":4,"vendor":2,"quantity":1}],"createdAt":{"$date":"2020-06-21T06:46:40.111Z"},"updatedAt":{"$date":"2020-07-09T11:04:04.459Z"},"__v":0,"totalPrice":265}
//const result = words.filter(word => word.length > 6);
//const f = cart.products.filter(p => p.vendor == 1);
const product = cart.products;
var grouped = product.reduce((dictionary, p) => {
dictionary[p.vendor] = dictionary[p.vendor] || [];
dictionary[p.vendor].push(p);
return dictionary;
}, {})
let vendor;
for (const p in grouped) {
console.log("vendor=", p, " count of items=", grouped[p].length)
}
I think this will give you the result you are looking for:
let f = cart.products.map( p => p.vendor);
let newArray = f.filter((vendor,index,arr)=>vendor!==arr[index+1]);
newArray.forEach(element => {
console.log(element);
});
You have some extraneous code in your script.
const result = words.filter(word => word.length > 6);
On line 36 you write const result = words.filter(word => word.length > 6); but words is not defined anywhere in your code and that is what generates the error.
For what concerns what you want to achieve, I am not entirely sure I understood it but, if I did, you can solve your issue like this:
const cart = {
"_id": 2,
"owner": 7,
"products": [{
"_id": {
"$oid": "5f06f9a4b8b878050fbc54b2"
},
"product": 1,
"vendor": 1,
"quantity": 2
}, {
"_id": {
"$oid": "5f06f9a4b8b878050fbc54b3"
},
"product": 2,
"vendor": 1,
"quantity": 1
}, {
"_id": {
"$oid": "5f06f9a4b8b878050fbc54b4"
},
"product": 4,
"vendor": 2,
"quantity": 1
}],
"createdAt": {
"$date": "2020-06-21T06:46:40.111Z"
},
"updatedAt": {
"$date": "2020-07-09T11:04:04.459Z"
},
"__v": 0,
"totalPrice": 265
}
const products = cart.products;
const vendors = products
.map(product => product.vendor)
.reduce((vendors, vendor) => {
if (vendors.indexOf(vendor) < 0) {
vendors.push(vendor);
}
return vendors;
}, []);
const productsByVendor = products.reduce((dictionary, p) => {
dictionary[p.vendor] = dictionary[p.vendor] || [];
dictionary[p.vendor].push(p);
return dictionary;
}, {});
console.log('Products grouped by vendor:\n', productsByVendor);
// in 'productsByVendor' the vendors are the keys of your object
console.log('Vendors:', Object.keys(productsByVendor));
/* if you want to retrieve the vendor of a specific product from 'productsByVendor'
* Assumptions:
* 1. cart.products[n].product is assumed to be a unique id (if that is not the case, you can use cart.products[n]._id instead)
* 2. I am assuming that each product can be sold by only one vendor; if a product can be sold by more than one vendor you'll have to adjust a bit the function
*/
getVendorIdFromGroupedProducts = (productId) => {
for (let key of Object.keys(productsByVendor)) {
for (let prod of productsByVendor[key]) {
if (prod.product === productId) {
return prod.vendor
}
}
}
return 'The product does not exist'
};
console.log('Vendor of product 1 is:', getVendorIdFromGroupedProducts(1));
console.log('Vendor of product 2 is:', getVendorIdFromGroupedProducts(2));
console.log('Vendor of product 3 is:', getVendorIdFromGroupedProducts(3));
console.log('Vendor of product 4 is:', getVendorIdFromGroupedProducts(4));