I'm training ruby and I need to do an exercice but I don't know how to get data
I have this
DB = [
{
title: "My first article",
content: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id ratione harum illo, dicta minima rerum quod natus cupiditate voluptatibus rem! Amet reprehenderit voluptatum animi, eligendi quia quos reiciendis veritatis magni.",
photo: "https://google.fr",
rating: "2"
},
{
title: "An second article",
content: "Eventually the guys with real ideas not running a scam on the world will overcome. I used an exclamation just to be an asshole and also to make a point! LOL Young Thug is super inspiring to me. Amazing artist!!! I also wanted to point out that it’s the first album to go number 1 off of streaming!!! ",
photo: "https://google.fr",
rating: "2"
},
{
title: "3 article",
content: "also to Kim’s hair and makeup Lorraine jewelry and the whole style squad at Balmain and the Yeezy team. When companies doubt me they doubt us. Wes daytime",
rating: "4"
},
]
COMMENTS = [
["Hello1"],
["comment2"],
["comment3"],
]
and I would like this
DATAS = [ {
title: "My first article",
content: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id ratione harum illo, dicta minima rerum quod natus cupiditate voluptatibus rem! Amet reprehenderit voluptatum animi, eligendi quia quos reiciendis veritatis magni.",
photo: "https://google.fr",
rating: "2"
}, ["Hello1"],
....
]
If you can me it's will be very hepful because table for me it's quite hard, Thank you
You didn't write any code, so I won't give you a complete answer.
You could get the desired result with Array#zip and Array#flatten.
flatten accepts an optional parameter for the number of nested arrays it should flatten.
So DB.zip(COMMENTS).flatten will be almost exactly what you want. You just need to provide the suitable parameter to flatten.
Related
I'm using gatsby-source-mysql to pull some data from an internal tool where our users are able to create advertisements that can be displayed on our consumer site. I currently have four promos set up for testing, and this is the GraphQL query that I have to pull that data:
query PromoQuery($id: String) {
allMysqlPromos(filter: { id: { eq: $id } }) {
edges {
node {
ad_title
ad_filename
ad_body
URL_ext
phone
id
}
}
}
}
This is what's being returned. It's getting all four promos, which is exactly what I need.
{
"data": {
"allMysqlPromos": {
"edges": [
{
"node": {
"ad_title": "Buy One, Get One Free",
"ad_filename": "ad_002910.jpg",
"ad_body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam turpis quam venenatis porta sed. Aliquet eget lobortis quam ut dignissim eget quam lobortis. Elementum, at nullam tincidunt viverra pulvinar ac porta sed mauris. Sit leo imperdiet turpis morbi arcu, posuere odio sit.",
"URL_ext": "/promo-one",
"phone": "19167137108",
"id": "mysql__Promos__2910"
}
},
{
"node": {
"ad_title": "Buy Two, Get Two Free",
"ad_filename": "ad_002911.jpg",
"ad_body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam turpis quam venenatis porta sed. Aliquet eget lobortis quam ut dignissim eget quam lobortis. Elementum, at nullam tincidunt viverra pulvinar ac porta sed mauris. Sit leo imperdiet turpis morbi arcu, posuere odio sit.",
"URL_ext": "/promo-two",
"phone": "19165451660",
"id": "mysql__Promos__2911"
}
},
{
"node": {
"ad_title": "Buy Three, Get Three Free",
"ad_filename": "ad_002912.jpg",
"ad_body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam turpis quam venenatis porta sed. Aliquet eget lobortis quam ut dignissim eget quam lobortis. Elementum, at nullam tincidunt viverra pulvinar ac porta sed mauris. Sit leo imperdiet turpis morbi arcu, posuere odio sit.",
"URL_ext": "/promo-three",
"phone": "19168243634",
"id": "mysql__Promos__2912"
}
},
{
"node": {
"ad_title": "New Year's Special",
"ad_filename": "ad_002913.jpg",
"ad_body": "Our amazing New Year's Special will guarantee you 50% off of 150 doors. If your house is big enough to have 150 doors then you deserve several thousand dollars off.",
"URL_ext": "/promo-four",
"phone": "19163654393",
"id": "mysql__Promos__2913"
}
}
]
}
}
}
However, in the template for the individual promos, I'm getting the same content on all four, and it is only returning data from the first node i.e. all four different promos have 'Buy One, Get One Free' as the main heading etc. Here is my template for the promo pages, including the GraphQL query from above.
/* eslint-disable react/display-name */
import React, { useContext, useEffect } from 'react';
import ShareImage from 'assets/images/one-day-share-slogan.png';
import { SEO } from 'components/seo/SEO';
import { Row } from 'containers/row/Row';
import { CallRail } from 'contexts/callrail-context/CallRailContext';
import { graphql } from 'gatsby';
import { Content } from './promo/content/_Content';
import { CallToAction } from './promo/cta/_CallToAction';
import { Hero } from './promo/hero/_Hero';
export default (props: any) => {
const document = props.data.allMysqlPromos.edges[0];
if (!document) return null;
const { changeNumber } = useContext(CallRail);
const number = document.node.phone;
useEffect(() => {
changeNumber(number);
});
console.log(document.node.ad_title);
return (
<>
<SEO
title={document.node.ad_title}
desc={document.node.ad_body.substr(0, 150) + '...'}
banner={ShareImage}
/>
<Hero document={document.node} />
<Row>
<CallToAction />
<Content>{document.node.ad_body}</Content>
</Row>
</>
);
};
export const query = graphql`
query PromoQuery($ad_title: String) {
allMysqlPromos(filter: { id: { eq: $ad_title } }) {
edges {
node {
ad_title
ad_filename
ad_body
URL_ext
phone
id
}
}
}
}
`;
What am I doing wrong, and what do I need to change to get the correct data in for each promo page?
You should pass via context your filter value, in that case, the ad_title field. So, in your gatsby-node.js you should have something like:
createPage({
path: `/promo/${URL_ext}`, // or your value
component: individualPromoComponent, // or your component
context: {
ad_title: node.ad_title,
},
})
Now, you can use ad_title in your component using $ad_title in:
export const query = graphql`
query PromoQuery($ad_title: String) {
allMysqlPromos(filter: { id: { eq: $ad_title } }) {
edges {
node {
ad_title
ad_filename
ad_body
URL_ext
phone
id
}
}
}
}
`;
I'm trying to insert data into my firebase JSon, which has the following structure
{
"gerechten" : [ {
"id" : "1",
"name" : "spaghetti",
"description" : "Spaghetti bolognese met veel liefde gemaakt op grootmoeders wijze.",
"kind" : "Pasta",
"preparation" : "1)Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",
"img" : "../../assets/img/gerechten/spaghetti.jpg",
"ingredients" : [ "5kg wortelen", "3 aardappelen", "1 komkommer", "2 eieren", "3 eetlepels bloem", "50g zout" ]
} ]
}
as you see, i got an array 'gerechten" and inside each array another array "ingredients". Right now i can add a items but i have no idea how to fill my "ingredients".
Is there a way to let the user give inputs and with each ',' there is a new ingredient? Eq;
5 eggs, 2 appels, 1 spoon of suger
sould create
"ingredients" : ["5 eggs", "2 appels", "1 spoon of suger"]
Also, as of now I have to insert my id manually, how can I make it so it takes automatic the next ID? when I leave the ID empty I got this result:
Firebase arror
Its does not put it inside an array
this is how i do it at the moment:
create.ts:
gerecht = {
description: "",
kind: "",
name: "",
prepartion: "",
ingredients: "",
id: "",
img: ""
}
create() {
this.db.create(this.gerecht.id, this.gerecht.description, this.gerecht.kind, this.gerecht.name, this.gerecht.prepartion, this.gerecht.img, this.gerecht.ingredients)
this.navCtrl.push(HomePage)
}
firedataservice:
create(id: string, description: string, kind: string, name: string, preparation: string, img: string, ingredients: string) {
this.db.object('gerechten/'+id).update({
id: id,
description: description,
kind: kind,
name: name,
preparation: preparation,
img: img,
ingredients: ingredients
})
}
Instead of returning an array of objects, pulling from a JSON file, it returns an array of 4 arrays containing 4 objects? Why? JSON file name is portfolios.json.
'use strict';
var portfolioArray = [];
function Portfolio (portfoliosDataObj) {
this.title = portfoliosDataObj.title;
this.body = portfoliosDataObj.body;
this.img = portfoliosDataObj.img;
}
Portfolio.prototype.toHtml = function() {
var renderPortfolios = Handlebars.compile($('#portfolio-template').text());
return renderPortfolios(this);
console.log(this);
};
$.getJSON('/data/portfolios.json', function(portfolios) {
portfolios.forEach(function(portfoliosDataObject) {
var portfolio = new Portfolio(portfoliosDataObject);
portfolioArray.push(portfolios);
console.log(portfolios);
});
});
function print () {
portfolioArray.forEach(function(data) {
$('#portfolioSection').append(data.toHtml());
});
}
Portfolio();
print();
JSON FILE - Adding for reference.
[{
"title": "CodeFellows/Code201",
"body": "content1",
"img": ""
},
{
"title": "CodeFellows/Code301",
"body": "lorem ipsum"
},
{
"title": "Upcoming Projects/Other interest",
"body": "lorem impsum",
"img": "/images/blog.jpg"
},
{
"title": "Illustrations",
"body": "lorem ipsum",
"img": "/images/portfolio.png"
}]
IGNORE need more content that isn't code to post....
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam porttitor leo at tellus facilisis, id suscipit ipsum suscipit. Aenean venenatis, quam semper efficitur hendrerit, odio diam condimentum odio, id sagittis lorem tellus vel mauris. Cras enim neque, malesuada sit amet lacinia et, ullamcorper non sapien. Integer id hendrerit nulla, vitae tristique tortor. Aenean in arcu eget massa pulvinar dictum. Aliquam dictum fermentum sapien id iaculis. Ut malesuada varius lacinia. Maecenas scelerisque facilisis mattis.
The file returns an array of 4 objects, and not arrays.
{
"title": "CodeFellows/Code201",
"body": "content1",
"img": ""
}
is a javascript object, not an array (notice the curly braces {}).
The outer one is an array. (notice the square brackets[]).
You can get to the objects by doing a console.log(portfolios[0]);
The issue is with this code. You are pushing portfolios in portfolioArray instead of portfolio. Also you were doing console.log for portfolios which is why it was showing 4 arrays. I have fixed the code. Let me know if it works for you.
$.getJSON('/data/portfolios.json', function(portfolios) {
portfolios.forEach(function(portfoliosDataObject) {
var portfolio = new Portfolio(portfoliosDataObject);
portfolioArray.push(portfolio);
console.log(portfolio);
});
});
I have an array of Mongoose ID's as follows:
var ids =[
mongoose.Types.ObjectId('58c2871414cd3d209abf4fc1'),
mongoose.Types.ObjectId('58c2871414cd3d209abf4fc0'),
mongoose.Types.ObjectId('58c2871414cd3d209abf5fc0')
];
When I call my Mongoose function to get the subdocuments that match these ids, the objects are returned to me in order of how they are found in the database. Can I reorder these based on the order of the above 'ids' array?
The data returned to me is as follows:
[ { _id: 58c2871414cd3d209abf5fc9,
companyname: 'Dell',
position:
{ _id: 58c2871414cd3d209abf5fc0,
title: 'Software Engineer',
location: 'Waterford',
start: 'May 2017',
term: 6,
description: ' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dsit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi' },
{ _id: 58ca9fd6588205e9c8f01431,
companyname: 'Google',
position:
{ _id: 58c2871414cd3d209abf4fc0,
title: 'Software Engineer',
location: 'Waterford',
start: 'May 2017',
term: 6,
description: ' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dsit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi' },
{ _id: 58ca9fd6588205e9c8f01431,
companyname: 'Google',
position:
{ _id: 58c2871414cd3d209abf4fc1,
title: 'Software Engineer',
location: 'Waterford',
start: 'June 2017',
term: 12,
description: ' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dsit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi' },
]
Is there any way of re-ordering these based on the original array? Note there are two _ids returned in the array, its the id for the position sub-document that I need to order. Really stuck if anyone could help that would be great!
EDIT:
My Node.js function is as follows:
var ids =[mongoose.Types.ObjectId('58c2871414cd3d209abf4fc0'), mongoose.Types.ObjectId('58c2871414cd3d209abf4fc1'), mongoose.Types.ObjectId('58c2871414cd3d209abf5fc0')];
User.aggregate( { $unwind : "$position" },
{ $match: { "position._id": {
$in: ids }
}
}
, function(err, results){
// results.sort((a, b) => {
console.log(a+" "+b);
// return ids.indexOf(mongoose.Types.ObjectId(a.position._id))
// - ids.indexOf(mongoose.Types.ObjectId(b.position._id))
// })
res.send({results:results});
});
});
Logged in console:
[object Object] [object Object]
[object Object] [object Object]
You can use Array.prototype.sort() with a compare function, the compare function finds the index of each element in ids using Array.prototype.indexOf() and giving it element.postion.id.
Here is the code:
data.sort((a, b) => {
return ids.indexOf(a.position._id) - ids.indexOf(b.position._id)
})
I used _id as a string, You have to change it to mongoose.Types.ObjectId()
I think it's done like that
data.sort((a, b) => {
return ids.indexOf(mongoose.Types.ObjectId(a.position._id)) - ids.indexOf(mongoose.Types.ObjectId(b.position._id))
})
I have a voting widget where visitors to a site can vote up or down on their favorite game. However, visitors are able to down vote to the negatives too!
For example, if the current voteCount on my game object on the scope is set to 0, a user can come along, press the down arrow and change it to -1. How can I stop this from happening?
I can do this manually by doing a check before the voting happens, but is there no angular filter to do this?
Also, what is the quickest way to allow a user a single vote instead of endless votes? Would cookies be the quickest way? or HTML5's LocalStorage?
CTRL CODE
myApp.controller('VotingCtrl', function($scope){
$scope.games = [
{
name: 'Watch Dogs',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut felis dapibus, bibendum dui eu.',
imgUrl: 'img/watchdogs.jpg',
voteCount: 0
},
{
name: 'Thief',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut felis dapibus, bibendum dui eu.',
imgUrl: 'img/thief.jpg',
voteCount: 0
},
{
name: 'Fifa 2014',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut felis dapibus, bibendum dui eu.',
imgUrl: 'img/fifa2014.jpg',
voteCount: 0
}
]
$scope.voteUp = function(game) {
game.voteCount += 1;
};
$scope.voteDown = function(game) {
game.voteCount -= 1;
};
});
One way is to change your voteDown method to not decrement if voteCount = 0.
The other way (which I would prefer) is to disable downVote button if the voteCount has reached 0, using ng-disabled. This will make it clear to the user that he/she cannot downvote anymore.
Edit: Pseudo Code for using ng-disabled.
In your view, you can do something like, assuming you are disabling a span.
<span ng-disabled="isDownVoteDisabled(game)"></span>
In your controller, you can define
$scope.isDownVoteDisabled = function(game) {
return game.voteCount <= 0;
}
Abhi.