// i have to change my data to this form
items={{
'2021-04-20': [{name: 'item 1 - any js object'}],
'2012-04-21': [{name: 'item 2 - any js object'}]
}}
I am trying to show data below using react-native calendar library's agenda. And agenda needs the form of data like above.
['20210420': 'work', '20210421': 'sleep'] //the data i have
how can i convert my data by using react-native code?
Maybe this can help you!
const data = {'20210420': 'work', '20210421': 'sleep'}
const formattedData = {}
Object
.entries(data)
.forEach(([key, value]) => formattedData[`${key.substr(0, 4)}-${key.substr(4, 2)}-${key.substr(6)}`]= [{ name: value }])
console.log(formattedData)
Related
I'm new to mongodb. And running a query and iterating a loop on it and inside loop I'm fetching data from another query and inserting it into the first one. But when I log the first query data outside the map iteration it does't show the second query data there. Below is my code:-
banner=await Banner.find({teacher:{$nin:exclude_academy},status:1})
.select('id position type type_id link banner amount')
.sort({position:1})
banner.map(async(bann)=>{
var course_data=await Course.findById(bann.type_id).exec();
course_data['type']='course';
bann['data']=course_data;
})
console.log(banner);
When I log the banner data it only shows first query data.
Below is my model structure:-
const mongoose=require('mongoose');
const Schema=mongoose.Schema({
teacher:{type:mongoose.Schema.Types.ObjectId, ref:"User", required:true},
position:{type:Number, default:0},
type:{type:String, required:true},
type_id:mongoose.Schema.Types.ObjectId,
image:{type:String, required:true},
amount:Number,
data:Object,
status:{type:Number, default:0},
data:Object
},
{
timestamps:true
});
module.exports=mongoose.model("Banner",Schema);
Finally, I solved it and here is the answer to the question. I need to call the callback function to get the data. Below is the complete code:-
var banner=await Banner.find({teacher:{$nin:exclude_academy},status:1})
.select('id position type type_id link banner amount')
.sort({position:1})
async function findData(type, type_id) {
var course_data=await Course.findById(type_id).exec();
course_data['type']='course';
course_data['purchase_status']=status;
return course_data;
}
await Promise.all(banner.map(async(bann)=>{
if (bann.type_id!='')
{
const data = await findData(bann.type,bann.type_id);
bann['data']=data;
}
}))
console.log(banner);
i'm having trouble with node & knex.js
I'm trying to build a mini blog, with posts & adding functionality to add multiple tags to post
I have a POST model with following properties:
id SERIAL PRIMARY KEY NOT NULL,
name TEXT,
Second I have Tags model that is used for storing tags:
id SERIAL PRIMARY KEY NOT NULL,
name TEXT
And I have many to many table: Post Tags that references post & tags:
id SERIAL PRIMARY KEY NOT NULL,
post_id INTEGER NOT NULL REFERENCES posts ON DELETE CASCADE,
tag_id INTEGER NOT NULL REFERENCES tags ON DELETE CASCADE
I have managed to insert tags, and create post with tags,
But when I want to fetch Post data with Tags attached to that post I'm having a trouble
Here is a problem:
const data = await knex.select('posts.name as postName', 'tags.name as tagName'
.from('posts')
.leftJoin('post_tags', 'posts.id', 'post_tags.post_id')
.leftJoin('tags', 'tags.id', 'post_tags.tag_id')
.where('posts.id', id)
Following query returns this result:
[
{
postName: 'Post 1',
tagName: 'Youtube',
},
{
postName: 'Post 1',
tagName: 'Funny',
}
]
But I want the result to be formated & returned like this:
{
postName: 'Post 1',
tagName: ['Youtube', 'Funny'],
}
Is that even possible with query or do I have to manually format data ?
One way of doing this is to use some kind of aggregate function. If you're using PostgreSQL:
const data = await knex.select('posts.name as postName', knex.raw('ARRAY_AGG (tags.name) tags'))
.from('posts')
.innerJoin('post_tags', 'posts.id', 'post_tags.post_id')
.innerJoin('tags', 'tags.id', 'post_tags.tag_id')
.where('posts.id', id)
.groupBy("postName")
.orderBy("postName")
.first();
->
{ postName: 'post1', tags: [ 'tag1', 'tag2', 'tag3' ] }
For MySQL:
const data = await knex.select('posts.name as postName', knex.raw('GROUP_CONCAT (tags.name) as tags'))
.from('posts')
.innerJoin('post_tags', 'posts.id', 'post_tags.post_id')
.innerJoin('tags', 'tags.id', 'post_tags.tag_id')
.where('posts.id', id)
.groupBy("postName")
.orderBy("postName")
.first()
.then(res => Object.assign(res, { tags: res.tags.split(',')}))
There are no arrays in MySQL, and GROUP_CONCAT will just concat all tags into a string, so we need to split them manually.
->
RowDataPacket { postName: 'post1', tags: [ 'tag1', 'tag2', 'tag3' ] }
The result is correct as that is how SQL works - it returns rows of data. SQL has no concept of returning anything other than a table (think CSV data or Excel spreadsheet).
There are some interesting things you can do with SQL that can convert the tags to strings that you concatenate together but that is not really what you want. Either way you will need to add a post-processing step.
With your current query you can simply do something like this:
function formatter (result) {
let set = {};
result.forEach(row => {
if (set[row.postName] === undefined) {
set[row.postName] = row;
set[row.postName].tagName = [set[row.postName].tagName];
}
else {
set[row.postName].tagName.push(row.tagName);
}
});
return Object.values(set);
}
// ...
query.then(formatter);
This shouldn't be slow as you're only looping through the results once.
I have a query that returns an array, with Object.key (array) .foreach I am iterating, I want to know the value of a property in specific array.
Example:
Object.keys(arreglo).forEach(function(key) {
console.log(arreglo[key]);
});
The output is:
name: "Pepito",
Surname: "Perez"
I want to know how to get only the value of the surname
I know it will not work but it would be something like:
console.log(arreglo[key].surname);
You can use Array.forEach on the original array as shown below. You can even extract the fields you are interested using Array.map.
// let's assume the arrary you got from your query is in this format
const arreglo = [
{ firstname: "fn1", surname: "ln1"},
{ firstname: "fn2", surname: "ln2"},
{ firstname: "fn3", surname: "ln3"}
];
// you can log `surname` for each entry in the array
arreglo.forEach(v => console.log(v.surname));
// you can use map to transform the array to just have `surname` using array.map()
const surnames = arreglo.map(v => v.surname);
console.log(surnames);
Is this what you are looking for
const object1 = {
a: {firstname:"sali",lastname:"mali"},
b: {firstname:"sali",lastname:"mali"},
c: {firstname:"sali",lastname:"mali"}
};
Object.keys(object1).forEach(function(key){console.log(object1[key].lastname)});
I am building a lambda on node.js and postgress database. When I query the database using :
client.query('SELECT name, age FROM user GROUP BY name')
I am getting an object like:
[['john', 35], ['mary', 26]]
what I want is to have on valid JSON, something like this:
[{"name" : "john", "age" : 35}, {"name" : "mary", "age" : 25}]
What is a good library or function that I can use to do this mapping? I tried JSON.parse and JSON.stringify but no luck.
Of course I can write a function myself to build a JSON object and populate it with the values coming from database but I want to see if there is a better way to that.
Thank you so much for the help
You can traverse through the array and make the desired json object
I put a sample code here
const myJsonObj = [];
const output = [['john', 35], ['mary', 26]];
for (let index=0; index<output.length; index++) {
const user = output[index];
const name = user[0];
const age = user[1];
myJsonObj.push({
name: name,
age: age,
});
}
console.log(myJsonObj);
It will produce the desired output, you mentioned
[ { name: 'john', age: 35 }, { name: 'mary', age: 26 } ]
You may make use of Postgres array_to_json and array_agg functions.
select array_to_json(array_agg(user_)) from user_;
This produces:
[{"name":"john","age":35},{"name":"mary","age":26}]
Demo
I am building using Node Google Actions client library version 2 to create a dynamic list using forEach or any other iterator in Node. Before I plough on does addList work with version 2 and if so does anyone have an example.
Hope someone can help but if not will do it myself and post up.
ditto for Carousel BTW but that should be very similar
Here is an example:
let items = {};
let array = ['first', 'second', 'third'];
array.forEach(element => {
items[element] = {
title: element,
image: new Image({
url: "url",
alt: "alt image title"
})
)}
})
conv.ask("List")
conv.ask(new List({
title: 'List',
items: items
)};