I have the following documents
{
"_id": "id",
"_rev": "123456",
"author": "john",
"views": "3",
},
{
"_id": "id",
"_rev": "123456",
"author": "jake",
"views": "5",
},
{
"_id": "id",
"_rev": "123456",
"author": "jake",
"views": "6",
},
{
"_id": "id",
"_rev": "123456",
"author": "john",
"views": "1",
},
{
"_id": "id",
"_rev": "123456",
"author": "jake",
"views": "7",
},
{
"_id": "id",
"_rev": "123456",
"author": "john",
"views": "10",
}
Lets suppose that these are comments and I would like to get the 2 most viewed comments by user.
How can I do that in CouchDB?
In any other sql database I could perform 2 queries with limit 2 and then merge the results.
If you have an array with that data in JavaScript you can simply use the sort method:
var a = [{...}, {...}, {...}];
a.sort(function(a, b) {
return b.views - a.views;
});
console.log(a[0]) //{ "_id": "id", "_rev": "123456", "author": "john", "views": "10" }
console.log(a[1]) //{ "_id": "id", "_rev": "123456", "author": "jake", "views": "7" }
If you want to only have the to most viewed records you can use the slice method
var a = [...];
a.sort(...);
a = a.slice(0, 2);
I guess you could just use this map:
function (doc) {
emit([doc.author, -doc.views], null);
}
without the reduce. Query with options ?startkey=['john']&limit=2 should result with something like:
{"total_rows":5,"offset":0,"rows":[
{"id":"id1","key":["john",-10],"value":null},
{"id":"id2","key":["john",-3],"value":null}
]}
Note the - sign when emitting doc.view to get biggest view count. You can also use descending=true option, but it will also reverse the order of the author string. This is not natural order for strings and you might need that in the future ;)
Related
I am not sure how to form this question, but I will do my best.
I don't know how to remove object by _id from 'list:' part.
So, I have one array, and inside of that array I have list of objects,inside of these objects I have again array with objects, so I want to remove one object from that last array, how I can do that?
Cannot fix it for 2 days, I'm stucked!
Thanks!
[
{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [
{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [
{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
]
Using Vanilla JS:
function findAndRemove(data, id) {
data.forEach(function(obj) { // Loop through each object in outer array
obj.list = obj.list.filter(function(o) { // Filter out the object with unwanted id, in inner array
return o._id != id;
});
});
}
var data = [{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
];
// Empty almost all of list, except middle one
findAndRemove(data, "599a1322bf50847b0972a384");
findAndRemove(data, "599a1322bf50847b0972a386");
findAndRemove(data, "599a12fdbf50847b0972a2a5");
findAndRemove(data, "599a12fdbf50847b0972a2a6");
findAndRemove(data, "599a12fdbf50847b0972a2ab");
console.log(data);
Cleared everything except middle list, just for better visualization.
#Abhijit Kar your one is working perfectly, thanks mate!
How I can later splice this list?
When I was working with objects from first array, I did it like this :
var inventory = jsonArrayList;
for (var i = 0; i < inventory.length; i++) {
if (inventory[i]._id == deleteProductById) {
vm.items.splice(i, 1);
break;
}
}
It would be very helpful, thanks alot!
You can use Array.map and Array.filter to accomplish this. Detailed explanation in comments:
PS: This snippet uses ES6 arrow functions and spread operator
function removeById(arr, id) {
// Array.map iterates over each item in the array,
// and executes the given function on the item.
// It returns an array of all the items returned by the function.
return arr.map(obj => {
// Return the same object, if the list is empty / null / undefined
if (!obj.list || !obj.list.length) return obj;
// Get a new list, skipping the item with the spedified id
const newList = obj.list.filter(val => val._id !== id);
// map function returns the new object with the filtered list
return { ...obj, list: newList };
});
}
const oldArray = <YOUR_ORIGINAL_ARRAY>;
const newArray = removeById(arr, "599a12fdbf50847b0972a2a5");
Here's an example of object from the JSON output of my database:
{
"id": "http://...",
"type": "example-type",
"title": "Example title",
"container-title": "Example container title",
"page": "1-100",
"issue": "3",
"URL": "http://www.url",
"ISSN": "0123-0123",
"author": [
{
"family": "Smith",
"given": "John"
}
],
"issued": {
"date-parts": [
[
"2000"
]
]
},
"keyword": "Sample Tag"
}
I've had enormous difficulties/bugs referring to the nested fields for author and date when building a data table. What I would like to do is somehow modify/flatten this before using it in the table (using Datatables' dataSrc as described here) and then simply call the restructured data as many times as I need using the datatables API.
So what I now refer to as issued.date-parts.0.0 would be simply year. The structure would be instead:
"authors": "John Smith", "Mark Smith"
"year": "2000"
Use the map function to get the authors
Look at this code snippet
var data = { "id": "http://...", "type": "example-type", "title": "Example title", "container-title": "Example container title", "page": "1-100", "issue": "3", "URL": "http://www.url", "ISSN": "0123-0123", "author": [ { "family": "Smith", "given": "John" }, { "family": "Smith", "given": "Mark" } ], "issued": { "date-parts": [ [ "2000" ] ] }, "keyword": "Sample Tag"};
var result = {
"authors": data.author.map((d) => `${d.given} ${d.family}`),
"year": data.issued['date-parts'][0][0]
}
console.log(result);
.as-console-wrapper {
max-height: 100% !important
}
I have a document that resembles:
[
{
"subscriberid": "4355",
"Title": "Miss",
"FirstName": "FirstName",
"LastName": "LastName",
"EmailAddress": "thisisanemail#email.com",
"Mobile": "",
"Postcode": "B1 3qq",
"Gender": "",
"SubscribeDate": "2015-08-12 10:58:29",
"Birthday": "31-5-1985",
"Kids": "no",
"Kidsages": "",
"Student": "no",
"Favourite": "1113111",
"attendreason": "Array",
"MarketingOptIn": "Y",
"Source": "WEBSITE",
"Login": [
{
"subscriberid": "4355",
"Created_at": "2017-05-18 10:09:44",
"IPaddress": "1.1.2.3"
}
]
},
{
"subscriberid": "125",
"Title": "",
"FirstName": "FirstName2",
"LastName": "LastName2",
"EmailAddress": "thisisalsoanemail#email.com",
"Mobile": "",
"Postcode": "tn39 4de",
"Gender": "",
"SubscribeDate": "2015-12-02 17:21:18",
"Birthday": "13-3-1922",
"Kids": "no",
"Kidsages": "",
"Student": "no",
"Favourite": "8108200",
"attendreason": "Date",
"MarketingOptIn": "Y",
"Source": "FACEBOOK",
"Vouchers": [
{
"subscriberid": "213",
"Created_at": "2017-05-18 08:57:47",
"Source": "some website",
"offer": "50offMains",
"name": "50% off Mains"
}
],
"Login": [
{
"subscriberid": "123",
"Created_at": "2017-05-18 07:57:46",
"IPaddress": "1.2.3.4"
}
]
}
]
And I'm trying to turn it into a CSV, automatically. Normally this would be a very simple script with json2csv, but for some reason this time I'm having an issue that I'm struggling to troubleshoot. My file is being created, but with headers only and no data.
I read the docs on https://github.com/zemirco/json2csv and I'm thinking I would use dot notation for the fields but due to how it's setup, I'm unsure what would preceed the dot?
I tried CLI version and an actual JS Version but same deal. All I get is the headers. As you'll see in the script, I only care about parts of the JSON Document, but even if I try to do it all, I still only get the headers. My previous versions have all used glob, but the CLI and pointing directly to the file still nets the same result.
var json2csv = require('json2csv');
var fs = require('fs');
var glob = require('glob');
let fields =
[
"subscriberid",
"Title",
"FirstName",
"LastName",
"EmailAddress",
"Mobile",
"Postcode",
"Gender",
"SubscribeDate",
"Birthday",
"Kids",
"Kidsages",
"Student",
"Favourite",
"attendreason",
"MarketingOptIn",
"Source"
];
let dataInput = glob("path/**/toFile.txt");
var csv = json2csv({ data: dataInput, fields: fields });
fs.writeFile('output.csv', csv, function(err) {
if (err) throw err;
console.log('file saved');
});
I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this
"result": [
{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
},
I am trying to test whether my response body has "name":"India" and the "game" with "some_game_id1" contains the "name":"cricket".
I went through this link where the answer is to have an array for "name"created and then check within the array whether the array contains the value. I tried this but my code fails.
Also, I tried searching the element by the index within the JSON body using this -
var searchJSON = JSON.parse(responseBody);
tests["name contains India"] = searchJSON.result.name[0]==="India";
But this also fails. I tried using the .value appended with the second line of above code, but it also fails. How can I check this thing?
You need to put [0] after result (which is an array) rather than name (which is a string).
Also, use a regular expression to check whether the name contains 'India', because using === only checks if the name is exactly India.
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
Demo Snippet:
var responseBody = `{
"result": [{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
}
]
}`
var tests = {}
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
console.log(tests) //=> { "name contains India": true }
I have JSON array with subarrays and I want to loop it and find if username of user is for example 'admin'. If so then create JSON array contains data belonging to user 'admin' (region, sport, city etc). I don't have idea how to find it in loop and then slice it. I'm sorry for stupid question but I'm a little lost.
This is JSON array with structure what I have:
[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
},
{
"_id": "552010740628cab002b3a700",
"region": {
"_id": "551e67b6d8f1afa01bd8652f",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "Bill",
"lastName": "Foo",
"username": "bill_foo",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e5e01abb74a8423410b88",
"nazev": "Hockey"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "some_title",
"created": "2015-04-04T16:25:24.733Z"
}
]
Edit:
the expected result of user 'admin' is then:
[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
}]
Loop through the array and pull out each item with a user with a username of admin:
var result = [];
var nameToSearchFor = 'admin';
for(var index = 0; index < arr.length; index++)
{
var item = arr[index];
if(item.user.username === nameToSearchFor)
{
result.push(item);
}
}
One solution to your problem is to search for the index that resides the admin username. In your case is at the 0 index of the json array provided. So you can get the entire object by the index, like this:
var i = 0;
for(; i< json.length; i++){
if(json[i].user.username === "admin") break;
}
With that now you can get the object with the admin data. Like this:
json[i].user.firstName
Check this plunk here
EDIT
If you want just to get that slice to a new array perhaps then you can just slice that piece of the json array, now that you have the index.
var newArray = json.slice(i, i+1);
You can use an open source project like jinqJs to perform SQL like queries on arrays.
var data = [
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
},
{
"_id": "552010740628cab002b3a700",
"region": {
"_id": "551e67b6d8f1afa01bd8652f",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "Bill",
"lastName": "Foo",
"username": "bill_foo",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e5e01abb74a8423410b88",
"nazev": "Hockey"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "some_title",
"created": "2015-04-04T16:25:24.733Z"
}
];
var result = jinqJs()
.from(data)
.where(function(row){return row.user.username==='admin';})
.select();
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>