Vue.js not arranging elements numerically? - javascript

So I tried getting Vue.js to arrange elements numerically by using "sortBy".
Obviously, I failed. I searched the web but got no satisfactory results, so anybody could help me?
HTML (not the whole thing, just the table that Vue.js renders)
<table class="ui celled table">
<thead>
<tr>
<th #click="sortBy='name'">Name</th>
<th #click="sortBy='cal'">Caliber</th>
<th #click="sortBy='r'">Range (max-min)(studs)</th>
<th #click="sortBy='dmg'">Damage</th>
<th #click="sortBy='cap'">Capacity</th>
<th #click="sortBy='rpm'">Rate of Fire</th>
<th #click="sortBy='multi'">Damage Multiplier (Head/Torso)</th>
<th #click="sortBy='desc'">Description</th>
<th #click="sortBy='rank'">Rank Unlock</th>
</tr>
</thead>
<tbody>
<tr v-for="list in lists">
<td>{{list.name}}</td>
<td>{{list.cal}}</td>
<td>{{list.r}}</td>
<td>{{list.dmg}}</td>
<td>{{list.cap}}</td>
<td>{{list.rpm}}</td>
<td>{{list.multi}}</td>
<td>{{list.desc}}</td>
<td>{{list.rank}}</td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="100%">{{sortedlists.length}} guns</th>
</tr>
</tfoot>
</table>
JS
new Vue({
el: "#main",
data: {
lists: [
{
"name": "M9",
"cal": "9Γ—19mm",
"dmg": "35-10",
"cap": "15+1 / 105",
"rpm": "780",
"multi":"1.50/1.10",
"desc": "A 9mm Italian pistol. One of the first 'wonder nines'. High capacity with deep reserves, light recoil, and high velocity. ",
"r": "40-80",
"rank": "0"
},
{
"name": "GLOCK 17 (G17)",
"cal": "9Γ—19mm",
"dmg": "34-10",
"cap": "17+1/102",
"rpm": "780",
"r":"40-90",
"multi":"1.50/1.10",
"desc": "A 9mm Austrian pistol renowned for its simplicity and ruggedness. Compared to the M9, it has a higher capacity, but less muzzle velocity.",
"rank": "1"
},
{
"name": "M1911",
"cal": ".45 ACP",
"dmg": "48-29",
"cap": "8+1/56",
"rpm": "720",
"r":"55-90",
"multi":"1.40/1.15",
"desc": "A classic American pistol brought into the modern age. Very high damage up close, with poor velocity and small magazine size.",
"rank": "2"
},
{
"name": "DESERT EAGLE (DEAGLE) L5",
"cal": ".44 MAGNUM",
"dmg": "56-32",
"cap": "8+1/40",
"rpm": "400",
"r":"50-80",
"multi":"2.00/ 1.30",
"desc": "A modern version of the iconic Israeli-American pistol. This specific model has been lightened as well as upgraded with dual Picatinny rails and a much-needed muzzle brake. Very high damage with the capacity to instantly kill to the head up close, with rough recoil.",
"rank": "3"
},
{
"name": "M45A1",
"cal": ".45 ACP",
"dmg": "45-28",
"cap": "10+1/60",
"rpm": "670",
"r":"50-95",
"multi":"1.40/1.15",
"desc": "A modern American pistol with many custom parts. High damage, medium capacity, strong recoil.",
"rank": "4"
},
{
"name": "FIVE SEVEN",
"cal": "5.7Γ—28mm",
"dmg": "29-22",
"cap": "20+1/100",
"rpm": "800",
"r":"80-120",
"multi":"1.40/1.20",
"desc": "A modern Belgian pistol firing a unique caliber. Poor close-in performance, with great ranged performance, high velocity, large magazine, wall penetration and deep reserves.",
"rank": "5"
},
{
"name": "ZIP 22",
"cal": ".22 LONG RIFLE",
"dmg": "15-12",
"cap": "10+1/180",
"rpm": "1000 SEMI",
"r":"30-60",
"multi":"2.80/1.00",
"desc": "A modern American 'pistol' with questionable quality. Abysmal damage, but with deep reserves and a high headshot multiplier. A weapon so bad it killed a million dollar company. 3 shots to the head at all ranges.",
"rank": "6"
},
.
.
.
.
etc all the way to "rank": "100"
{
"name": "MG42**",
"cal": "7.62 NATO",
"dmg": "36-20",
"cap": "50/250",
"rpm": "1200 AUTO",
"multi":"1.40/1.00",
"desc": "The original, the iconic, the feared... The buzzsaw of the axis powers during the second world war, back to prove it’s worth in the modern warzone. Fires extremely fast and hits even harder, but is slow and inaccurate.",
"rank": "100"
},
],
sortBy: "rank",
filterByName: "",
counter: 0
},
computed: {
sortedlists() {
return this.lists.filter(
list => list.name.includes(this.filterByName)
).sort(
(a, b) => a[this.sortBy].localeCompare(b[this.sortBy])
);
}
}
});
EDIT: I didn't include the whole javascript so I thought I might as well update the questions to make it clearer. So as I said, the `
computed:
{
sortedlists() {
return this.lists.filter(
list => list.name.includes(this.filterByName)
).sort(
(a, b) => a[this.sortBy].localeCompare(b[this.sortBy])
);
}`
doesn't arrange the elements in numerical order.
etc. all the way to "rank": "100".
Vue arranges the elements in a way like 0,1,10,100,11,2,20,21........29,3,30,31,32,33,.....39,4,40,....48,49 etc
You get the idea. It just doesn't seem to arrange the elements like 1,2,3,4,5,6,7,8,9,10,11,12 etc. which I want it to do.
Any helpful answers?

You need to sort by rank as a number and not as a string. Alphabetical order is exact that you got: 1,10,100,11,2,20,21.
const sortedList = lists.splice().sort((x1, x2) => (parseInt(x1.rank) - parseInt(x2.rank)))

Ahhhh seems like I found the answer after some serious tinkering with the code.
I changed it to the following:
computed: {
sortedlists() {
return this.lists.filter(
list => list.name.includes(this.filterByName)
).sort(
(a, b) => a[this.sortBy] - b[this.sortBy]
);
}
}

Related

How do I display json data using Reactjs?

I have products.json in which I have data. Now, I wish to render it using Reactjs.
products.json
[
{
"id": 1,
"productName": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
"price": 109.95,
"description": "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
"specification": {}
},
{
"id": 2,
"productName": "Mens Casual Premium Slim Fit T-Shirts ",
"price": 22.3,
"description": "Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg",
"specification": {}
}
]
app.js
function App(){
return(
)
}
I want the json data to be rendered through app.js.
My Take On:
I'm new to Reactjs and JSON and was thinking of using fetch, response but I'm not sure how can I do it.
Can someone please help?
First you have to put your data in variable
For example:
const data = [
{
"id": 1,
"productName": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
"price": 109.95,
"description": "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
"specification": {}
},
{
"id": 2,
"productName": "Mens Casual Premium Slim Fit T-Shirts ",
"price": 22.3,
"description": "Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion
wear and diehard baseball fans. The Henley style round neckline includes a three-button
placket.",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg",
"specification": {}
}
]
The you have to map through your array
Like this
function App(){
return (
<div>
{data.map((d) => (
<div key={d.id}>
<p>ID: {d.id}</p>
<p>Product Name: {d.productName}</p>
<p>Price: {d.price}</p>
<p>Description: {d.description}</p>
<p>Category: {d.category}</p>
<p>
Image: <img src={d.image} width="100" />
</p>
<br />
<br />
</div>
))}
</div>
);
}
Then you can add CSS to make it look better!

Can't parse a JSON file

I started learning node.js and I am facing an error.
Here's the code:
const server = http.createServer((req, res) =>{ //request, response
const pathName = req.url;
if (pathName === '/' || pathName === '/overview'){
res.end('This is the OVERVIEW') // res trimite catre client, req trimite catre server
} else if (pathName === '/product'){
res.end('This is the PRODUCT');
} else if (pathName === '/api') {
fs.readFile(`${__dirname}/dev-data/data.json`, 'utf-8', (err, data) => {
const productData = JSON.parse(data);
response.writeHead(200, { 'Content-type': 'application/json' });
response.end(data);
});
} else{
res.writeHead(404, {
'Content-type': 'text/html',
'my-own-header': 'hello-world'
});
res.end('<h1>This page could not be found!</h1>');
}
res.end('Hello from the server!');
});
the problem is in this if:
else if (pathName === '/api') {
fs.readFile(`${__dirname}/dev-data/data.json`, 'utf-8', (err, data) => {
const productData = JSON.parse(data);
response.writeHead(200, { 'Content-type': 'application/json' });
response.end(data);
});
The error i get:
undefined:1
undefined
^
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse ()
at ReadFileContext.callback (c:\Users\40721\Desktop\nodeJs&Express\complete-node-bootcamp-master\1-node-farm\index.js:49:38)
at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:257:13)
The data.json file i want to read from is this:
[
{
"id": 0,
"productName": "Fresh Avocados",
"image": "πŸ₯‘",
"from": "Spain",
"nutrients": "Vitamin B, Vitamin K",
"quantity": "4 πŸ₯‘",
"price": "6.50",
"organic": true,
"description": "A ripe avocado yields to gentle pressure when held in the palm of the hand and squeezed. The fruit is not sweet, but distinctly and subtly flavored, with smooth texture. The avocado is popular in vegetarian cuisine as a substitute for meats in sandwiches and salads because of its high fat content. Generally, avocado is served raw, though some cultivars, including the common 'Hass', can be cooked for a short time without becoming bitter. It is used as the base for the Mexican dip known as guacamole, as well as a spread on corn tortillas or toast, served with spices."
},
{
"id": 1,
"productName": "Goat and Sheep Cheese",
"image": "πŸ§€",
"from": "Portugal",
"nutrients": "Vitamin A, Calcium",
"quantity": "250g",
"price": "5.00",
"organic": false,
"description": "Creamy and distinct in flavor, goat cheese is a dairy product enjoyed around the world. Goat cheese comes in a wide variety of flavors and textures, from soft and spreadable fresh cheese to salty, crumbly aged cheese. Although it’s made using the same coagulation and separation process as cheese made from cow’s milk, goat cheese differs in nutrient content."
},
{
"id": 2,
"productName": "Apollo Broccoli",
"image": "πŸ₯¦",
"from": "Portugal",
"nutrients": "Vitamin C, Vitamin K",
"quantity": "3 πŸ₯¦",
"price": "5.50",
"organic": true,
"description": "Broccoli is known to be a hearty and tasty vegetable which is rich in dozens of nutrients. It is said to pack the most nutritional punch of any vegetable. When we think about green vegetables to include in our diet, broccoli is one of the foremost veggies to come to our mind. Broccoli is a cruciferous vegetable and part of the cabbage family, which includes vegetables such as Brussel sprouts and kale. Although the tastes are different, broccoli and these other vegetables are from the same family."
},
{
"id": 3,
"productName": "Baby Carrots",
"image": "πŸ₯•",
"from": "France",
"nutrients": "Vitamin A, Vitamin K",
"quantity": "20 πŸ₯•",
"price": "3.00",
"organic": true,
"description": "The carrot is a root vegetable that is often claimed to be the perfect health food. It is crunchy, tasty and highly nutritious. Carrots are a particularly good source of beta-carotene, fiber, vitamin K, potassium and antioxidants. Carrots have a number of health benefits. They are a weight loss friendly food and have been linked to lower cholesterol levels and improved eye health."
},
{
"id": 4,
"productName": "Sweet Corncobs",
"image": "🌽",
"from": "Germany",
"nutrients": "Vitamin C, Magnesium",
"quantity": "2 🌽",
"price": "2.00",
"organic": false,
"description": "Also known as maize, corn is one of the most popular cereal grains in the world. Popcorn and sweet corn are commonly eaten varieties, but refined corn products are also widely consumed, frequently as ingredients in foods. These include tortillas, tortilla chips, polenta, cornmeal, corn flour, corn syrup, and corn oil. Whole-grain corn is as healthy as any cereal grain, rich in fiber and many vitamins, minerals, and antioxidants."
}
]
Are you storing the image property as a location to the image? JSON only accepts these datatypes:
a string
a number
an object (JSON object)
an array
a boolean
null

What algorithm can perform string pattern search JS?

In the frontend there is a list of game titles that consist of strings:
id, game name, date, price
The search shall accept multiple keywords, e.g. user might type: 1998 Streetfighter 2 or Streetfighter 1998 Currently I create an array separated by empty space, that creates 3 keywords: [1998, Streetfighter , 2 ] Then I go through the collection of game titles to filter matches. unfortunately it also gives back any title that includes "2" because there is no pattern recognition that identifies "Streetfighter 2" belongs together. Is there a simple algorithm to provide a pattern search?
const allGames = [
"Streetfighter 1, 1992, 20",
"Streetfighter 2, 1998, 20",
"pokemon, 2016, 20",
"Diablo 3, 2015, 40",
"Super mario, 1995, 20",
"The Witcher, 2012, 20",
]
Your search query looks advanced enough to justify using a search engine. Just don't create one yourself (it's harder than you may think).
In this answer I'll be using Lunr.js
Here's a 2min crash course:
Transform your data into documents. (I've already converted your initial allGames array.)
Then create a search index where you:
Specify which property of a document holds a unique identifier. (In our case title.)
Define which properties should be indexed. (In our case all of them.)
Define a boost score for each property. (i.e a match in the title has a higher relevance score than a match in the price.)
Add all documents to the search index.
Search! ;)
πŸ“’ Search Query FTW!
Notice the last search, I'm using a wildcard in the search string (street*) to find the two Street Fighter titles!
const createLunrIndex = docs =>
lunr(function () {
this.ref('title');
this.field('title', 5);
this.field('date', 3);
this.field('price', 1);
for (doc of docs) this.add(doc);
});
const search = (lunrIndex, term) =>
lunrIndex
.search(term)
.map(res => res.ref)
const gamesIndex = createLunrIndex(allGames);
console.log(
search(gamesIndex, '1998 Streetfighter 2')
);
console.log(
search(gamesIndex, 'Streetfighter 1998')
);
console.log(
search(gamesIndex, 'street*')
);
<script src="https://unpkg.com/lunr/lunr.js"></script>
<script>
const allGames =
[ { "title": "Streetfighter 1"
, "date": "1992"
, "price": "20"
}
,
{ "title": "Streetfighter 2"
, "date": "1998"
, "price": "20"
}
,
{ "title": "pokemon"
, "date": "2016"
, "price": "20"
}
,
{ "title": "Diablo 3"
, "date": "2015"
, "price": "40"
}
,
{ "title": "Super mario"
, "date": "1985"
, "price": "20"
}
,
{ "title": "The Witcher"
, "date": "2012"
, "price": "20"
}
]
</script>

Can you automate adding products from an online store to WooCommerce?

I would like to get all the products from an account on this Dutch webshop (similar to eBay/Amazon) and add them to this WordPress webshop using WooCommerce. I started web development about 2 to 3 weeks ago, and I know the basics of HTML, CSS, JavaScript, Nodejs, and Express. I think I know roughly what to do, that is:
Iterate over all the products per page.
Grab the title, description, category, price, and photo.
Store that information in an array with product objects.
Get access to WooCommerce API.
Iterate over all the products and add them to WooCommerce.
My questions are:
Is this possible?
Can I do it with the languages available to me?
What methods would you use? (e.g. how would you scrape the HTML, is there an easier way than the steps I described, would you do this using code or rather using some automation software, etc.)
This is a big project for me, so any help (on how to start) is welcome!
You are right about the steps and yes that is possible. You can scrape the data with node.js as you know already, my personal preference is python when it comes to data scraping but you can do it in node.js. Node.js has HTML parser and so on. I would suggest you a few things:
Parse the HTML data with a parser to get better access to the elements in order to get the data.
Use some kind of data structure to store the data properly, for example: JSON, XML, CSV...
If getting the data is a long process, get the data first as you may lose all the data while parsing if any section in your parsing system doesn't suit, parse the data afterwards.
I will bring here the code I wrote to get the data from the website you put, it's in python language but I put comments on it so you can get a better understanding about how you can get the data and write in other languages. You can also use split to cut the sections from HTML data, you don't even need to use a parser.
Example:
import requests, json
from bs4 import BeautifulSoup
from pprint import pprint
endpoint = "http://johndevisser.marktplaza.nl/?p=1"
# Send a get request to page to get the html.
data = requests.get(endpoint).content
# Parse the html via BeautifulSoup
page = BeautifulSoup(data)
# Find 'div' elements whose 'itemscope' attributes are 'itemscope'
products = page.find_all("div", {"itemscope": "itemscope"})[1:]
# Create an empty array to store prepared data.
finalProductList = []
# Iterate over the products.
for i in products:
# Create a dictionary object to store data properly.
productData = {}
# Get the title attribute from 'a' element on the current product.
productData["title"] = i.find("a").get("title")
# Get the href attribute from 'a' element on the current product because the real source can be useful in the future.
productData["origin"] = i.find("a").get("href")
# Get the image url from 'img' elements to download images.
productData["imageURL"] = i.find("img").get("src")
# This may look you complicated but it just finds 'span' elements value of 'class' attribute is 'subtext' and get the
# inner text, split into two from ' '(space) to this ['€', '15,00'] and get the right part which is the second part
# in the array which is the price and replace comma with dot to parse in float value.
productData["price"] = float(i.find("span", {"class": "subtext"}).get_text().split(u"\xa0")[1].replace(",", "."))
# Append the data to final data array.
finalProductList.append(productData)
# Get json representation of dictionary.
print(json.dumps(finalProductList))
Output:
[
{
"title": "Sieb Posthuma - Mannetje Jas (Hardcover/Gebonden) Kinderjury",
"origin": "http://www.marktplaza.nl/boeken/kinderboeken/sieb-posthuma-mannetje-jas-hardcover-gebonden-kinderjury-92409632.html",
"imageURL": "http://www.marktplaza.nl/M92409632/1/sieb-posthuma-mannetje-jas-hardcover-gebonden-kinderjury-92409632.jpg",
"price": 12.5
},
{
"title": "Estefhan Meijer - United Wraps Wraps Uit De Hele Wereld",
"origin": "http://www.marktplaza.nl/boeken/kookboeken/estefhan-meijer-united-wraps-wraps-uit-de-hele-wereld-92390218.html",
"imageURL": "http://www.marktplaza.nl/M92390218/1/estefhan-meijer-united-wraps-wraps-uit-de-hele-wereld-92390218.jpg",
"price": 15
},
{
"title": "Daphne Deckers - De Verschrikkelijke Ijstaart (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/kookboeken/daphne-deckers-de-verschrikkelijke-ijstaart-hardcover-gebonden-92390182.html",
"imageURL": "http://www.marktplaza.nl/M92390182/1/daphne-deckers-de-verschrikkelijke-ijstaart-hardcover-gebonden-92390182.jpg",
"price": 10
},
{
"title": "Adelene Fletcher - Bomen Aquarelleren Van A Tot Z",
"origin": "http://www.marktplaza.nl/boeken/hobby-techniek/adelene-fletcher-bomen-aquarelleren-van-a-tot-z-92390124.html",
"imageURL": "http://www.marktplaza.nl/M92390124/1/adelene-fletcher-bomen-aquarelleren-van-a-tot-z-92390124.jpg",
"price": 12.5
},
{
"title": "Razorlight β€Žβ€“ America (2 Track CDSingle)",
"origin": "http://www.marktplaza.nl/cd-vinyl/singles/razorlight-america-2-track-cdsingle-92390118.html",
"imageURL": "http://www.marktplaza.nl/M92390118/1/razorlight-america-2-track-cdsingle-92390118.jpg",
"price": 5
},
{
"title": "Twarres β€Žβ€“ Children (2 Track CDSingle)",
"origin": "http://www.marktplaza.nl/cd-vinyl/singles/twarres-children-2-track-cdsingle-92390078.html",
"imageURL": "http://www.marktplaza.nl/M92390078/1/twarres-children-2-track-cdsingle-92390078.jpg",
"price": 5
},
{
"title": "Tower Of Power β€Žβ€“ The Very Best Of Tower Of Power - The Warner Years (CD)",
"origin": "http://www.marktplaza.nl/cd-vinyl/pop/tower-of-power-the-very-best-of-tower-of-power-the-warner-years-cd-92389836.html",
"imageURL": "http://www.marktplaza.nl/M92389836/1/tower-of-power-the-very-best-of-tower-of-power-the-warner-years-cd-92389836.jpg",
"price": 10
},
{
"title": "Red Hot Chili Peppers β€Žβ€“ Dani California (2 Track CDSingle)",
"origin": "http://www.marktplaza.nl/cd-vinyl/singles/red-hot-chili-peppers-dani-california-2-track-cdsingle-92389742.html",
"imageURL": "http://www.marktplaza.nl/M92389742/1/red-hot-chili-peppers-dani-california-2-track-cdsingle-92389742.jpg",
"price": 5
},
{
"title": "Seth Godin - Icarus Deception (Engelstalig)",
"origin": "http://www.marktplaza.nl/boeken/management-en-economie/seth-godin-icarus-deception-engelstalig-92389542.html",
"imageURL": "http://www.marktplaza.nl/M92389542/1/seth-godin-icarus-deception-engelstalig-92389542.jpg",
"price": 12.5
},
{
"title": "Rob Gifford - De Chinese Weg",
"origin": "http://www.marktplaza.nl/boeken/reizen/rob-gifford-de-chinese-weg-92389500.html",
"imageURL": "http://www.marktplaza.nl/M92389500/1/rob-gifford-de-chinese-weg-92389500.jpg",
"price": 12.5
},
{
"title": "Bart Leeuwenburgh - Darwin In Domineesland",
"origin": "http://www.marktplaza.nl/boeken/informatief/bart-leeuwenburgh-darwin-in-domineesland-92386128.html",
"imageURL": "http://www.marktplaza.nl/M92386128/1/bart-leeuwenburgh-darwin-in-domineesland-92386128.jpg",
"price": 12.5
},
{
"title": "Per Olov Enquist - Het Record (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/romans/per-olov-enquist-het-record-hardcover-gebonden-92386080.html",
"imageURL": "http://www.marktplaza.nl/M92386080/1/per-olov-enquist-het-record-hardcover-gebonden-92386080.jpg",
"price": 10
},
{
"title": "Fred Vargas - Uit De Dood Herrezen (Hardcover/Gebonden) blauw/groene achtergrond",
"origin": "http://www.marktplaza.nl/boeken/romans/fred-vargas-uit-de-dood-herrezen-hardcover-gebonden-blauw-groene-achtergrond-92385368.html",
"imageURL": "http://www.marktplaza.nl/M92385368/1/fred-vargas-uit-de-dood-herrezen-hardcover-gebonden-blauw-groene-achtergrond-92385368.jpg",
"price": 12.5
},
{
"title": "Fred Vargas - De Omgekeerde Man (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/romans/fred-vargas-de-omgekeerde-man-hardcover-gebonden-92385304.html",
"imageURL": "http://www.marktplaza.nl/M92385304/1/fred-vargas-de-omgekeerde-man-hardcover-gebonden-92385304.jpg",
"price": 15
},
{
"title": "David Sandes - Sergei Bubka's Wondermethode (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/romans/david-sandes-sergei-bubkas-wondermethode-hardcover-gebonden-92385090.html",
"imageURL": "http://www.marktplaza.nl/M92385090/1/david-sandes-sergei-bubkas-wondermethode-hardcover-gebonden-92385090.jpg",
"price": 10
},
{
"title": "Sjoerd Kuyper - Sjaantje Doet Alsof (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/kinderboeken/sjoerd-kuyper-sjaantje-doet-alsof-hardcover-gebonden-92384948.html",
"imageURL": "http://www.marktplaza.nl/M92384948/1/sjoerd-kuyper-sjaantje-doet-alsof-hardcover-gebonden-92384948.jpg",
"price": 10
},
{
"title": "Het Piratenschip Klap Open En Bekijk (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/kinderboeken/het-piratenschip-klap-open-en-bekijk-hardcover-gebonden-92371996.html",
"imageURL": "http://www.marktplaza.nl/M92371996/1/het-piratenschip-klap-open-en-bekijk-hardcover-gebonden-92371996.jpg",
"price": 12.5
},
{
"title": "John Topsell - Draken Trainen En Verzorgen (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/kinderboeken/john-topsell-draken-trainen-en-verzorgen-hardcover-gebonden-92371928.html",
"imageURL": "http://www.marktplaza.nl/M92371928/1/john-topsell-draken-trainen-en-verzorgen-hardcover-gebonden-92371928.jpg",
"price": 15
}
]

Join on multiple ids from the same table

I'm trying to join a two tables (versus and words) on multiple ids. I don't really know how to explain it, so I'm just going to show what I mean.
An excerpt from the versus-table:
{
"date": 1427675857789,
"hero": "7b88a237-c288-48f1-bf45-2dcd9f812b54",
"id": "017fe06a-e37d-4f23-92a3-bc52b38de4d7",
"nemesis": "e87a6252-6d08-4c5a-b057-2718e8c07d93",
"points": {
"hero": 58659,
"nemesis": 3021
}
}
Excerpt from the words-table:
{
"id": "7b88a237-c288-48f1-bf45-2dcd9f812b54" ,
"word": "i"
},
{
"id": "e87a6252-6d08-4c5a-b057-2718e8c07d93" ,
"word": "the"
}
I'd like to join the two tables so get something like this:
{
"date": 1427675857789,
"hero": "i",
"nemesis": "the",
"points": {
"hero": 58659,
"nemesis": 3021
}
}
This is what I have so far: r.table("versus").eqJoin("hero", r.table("words")).zip(), which gets me this:
{
"date": 1427675857789 ,
"hero": "7b88a237-c288-48f1-bf45-2dcd9f812b54" ,
"id": "7b88a237-c288-48f1-bf45-2dcd9f812b54" ,
"nemesis": "e87a6252-6d08-4c5a-b057-2718e8c07d93" ,
"points": {
"hero": 60507 ,
"nemesis": 3504
} ,
"word": "i"
}
I'm a little puzzled about how I can join it on the hero-row as well as nemesis-row.
Though I'd be happy with any result that shows most of the things from the versus-table (Doesn't matter if id is there) and two the two words which corresponds to the hero and nemesis id.
EDIT: I've figured something out, but now I'm only able to get the first document, which kind of defeats the purpose of what I'm trying to do... Here's what I got: r.table("versus").eqJoin("hero", r.table("words")).zip().map(r.row.merge({hero: r.row("word")})).eqJoin("nemesis", r.table("words")).zip().map(r.row.merge({nemesis: r.row("word")})).without(["word", "id"])
Well, I did it...finally!
If someone's interested, this is what my new ReQL looks like:
r.table("versus").concatMap(function(v){
return r.table("words").getAll(v("hero"), {index: "id"}).map(function(w){
return r.branch(
v("hero").eq(w("id")),
v.merge({hero: w("word")}),
v
)
})
}).concatMap(function(v){
return r.table("words").getAll(v("nemesis"), {index: "id"}).map(function(w){
return r.branch(
v("nemesis").eq(w("id")),
v.merge({nemesis: w("word")}),
v
)
})
}).without("id")

Categories

Resources