DataviewJS Snippet Showcase

Hi, does somebody have some example on how to get all Values from a Specific Key from all notes with a specific tag?
Plus the values should be stored in an array with value, value (as I need it for templater suggester).

Possibly useful: you can use Dataview DQL queries inside dataviewjs if it is easier to express a query that way. e.g. dv.tryQuery('LIST WITHOUT ID SpecificKey FROM #tag').values should give you a list of the values you want, but there will be duplicates so you probably want to convert the result to a Javascript Set before mapping to the [value, value] array format that you want.

1 Like

I’m not getting there (lack of JS knowledge)

let pages = dv.pages("#content/code")
let allPrograms = pages.map(a => a.program);
let uniqPrograms = allPrograms.filter((item, index) => allPrograms.indexOf(item) === index)

creates a Proxy { values: Array(5)… in console, what I need is {key: value, key: value… in console. If I replace a.program with [a.program, a.program] I get arrays in arrays… :disappointed:

btw: 5 is correct… it is normally 6 but one duplicate.

So I have the following problems:
a) how to get the correct datastructure
b) how to remove duplicates from that
c) how to remove undefined from that

1 Like

Can anyone advise if its possible to populate a TaskList nested within a Table row? I’m trying to incorporate this, but when I attempt this, I’m left with fields within the actual table rows, and the TaskList rendered above the table.

Sample Markdown (codeblock tildes replaced with apostrophes):

'''dataviewjs
let md = dv.current().file.tasks
dv.table([" "], 
	md.map(m => [dv.taskList([m])])
	)
'''

- [ ] this task
- [ ] that task

Outcome:
image

i want to construct a dataviewjs table to show only the events coming in say september. i also have tags. Can someone help in the dataview query. i tried but was not able to construct based on september month

I also tried to do this via reactjs components but failed to get the data inside a md file. Hence now trying this via dataviewjs

below are my contents in md file:

Autumn starting | 2022-09-03 #event
Winter starting | 2022-11-03 #event
Birthday | 2022-12-03 #birthday
one more | 2022-10-23 #anniversary

You can have a look at my upcoming event calendar here, it should give you some pointers.

It creates a visual calendar view of all upcoming events:

this is my weekly statistic graph
image
image
image

I’m trying to build the DataviewJS query. That is extracting the vault path and building the full path for image by combining YAML Header where I have only name of the image with extension as string

YAML Header

name: Original
number: 1
image: "image12.jpg"
sphere: Earth

DataviewJS query

dataviewjs

//@ts-ignore

let adapter = app.vault.adapter;

 // VAULT PATH
const vault = adapter.getBasePath();

 // PATH WHERE I HAVE IMAGES
const vault_images = vault + "/Resources/Images/"

const pages = 
		dv.pages()
		.where(b => b.file.frontmatter.sphere === 'Earth')
		.sort(b => b.file.frontmatter.number)
		.array()
	.map(({file}) => {

 // PROBLEMATIC LINE
	return ["![](" + vault_images + file.frontmatter.image + ")",file.name, file.frontmatter.number]
})

dv.table(["Image", "Name", "Number"], pages)

Result

It gives me the table of all items, but there is just one image propery for all records. It looks like it is giving me all images as object.


I will really appreciate somebody who can help me to adjust the code :pray:t2:

Love it

1 Like

SHOW IMAGE BASED ON YAML PARAMETER

IMAGE FILE: base_color.jpg

Note

---
date:
image: color
tags: 
---
dataviewjs

const prefix = "base"      /// image prefix
const ext = ".jpg"         /// image extension
const size = "200"         /// image size

const cover = "![[" + prefix + "_" + dv.current().image + ext + "|" + size + "]]"
dv.paragraph(cover)
2 Likes

I am using $=dv.pages().length in a vault info bar to show the total number of files in the vault but I want to also have a inline snipped that shows the number of files modified today, what code would I use?

  • You could use the following Inline DataviewJS Query.

### inDVJS10
QTY_modified_today=`$=dv
    .pages()
    .where((page) => page.file.mday.toFormat("yyyy-MM-dd") === dv.func.date("today").toFormat("yyyy-MM-dd")).length;`

1 Like

Topic

Summary
  • How to filter the data by the filename of a link from the Markdown files with the case_YAML_Y-YYY structure?

Structures: case_YAML_Y-YYY

Summary

TIP:
1.AoH in the topic means an Array of Hashes.
2.Hashes in the topic means JavaScript Objects.

Definitions:

Structure Code: case_YAML_Y-YYY
Definitions: Use nested YAML fields, where a single root YAML field which is an Array of Hashes consists of
at least one Hash, which is represented by sub YAML fields “-YYY”.

YAML: Use YAML.
Y: a single root YAML field which is an Array of Hashes
-YYY: at least one Hash, which is represented by sub YAML fields “-YYY”

The first sub YYY, an element of the root Y, consists of multiple key/value pairs, as known as a Hash.
The second sub YYY, an element of the root Y, consists of multiple key/value pairs, as known as a Hash.

Data Structure: an AoH
Original Structure Code expressed in regular expressions: case_YAML_Y(-YYY){1,}

Basic Example: The AoH drinks consists of two elements with the data type of a Hash.

NOTE:
Take the following file db_20220110 as an example.
Y: drinks, which is an AoH
-YYY: The first sub YYY, an element of the root Y, contains multiple key/value pairs, as known as a Hash.
-YYY: The second sub YYY, an element of the root Y, contains multiple key/value pairs, as known as a Hash.

```yaml
---
Date: 2022-01-10

drinks:
  # The first sub YYY
  - item_name: "Black Coffee"
    unit_price: 120
    caffeine_content: 300
    item_no: "IT001"
  # The second sub YYY
  - item_name: "Green Tea"
    unit_price: 100
    caffeine_content: 200
    item_no: "IT002"
---

```

Basic Example: The AoH drinks consists of one element with the data type of a Hash.

NOTE:
Take the following file db_20220111 as an example.
Y: drinks, which is an AoH
-YYY: The first sub YYY, an element of the root Y, contains multiple key/value pairs, as known as a Hash.

```yaml
---
Date: 2022-01-11

drinks:
  # The first sub YYY
  - item_name: "Apple Juice"
    unit_price: 110
    caffeine_content: 0
    item_no: "IT003"

---

```

Notes:

Summary

Q1: What is the data structure of the file dic_19920301?

Summary_Q1
Original Example: Q1 (To be explained)

NOTE:
Take the following file dic_19920301 as an example.

```yaml
---
date: 1992-03-01
purchases:
  - store: "[[some store]]"
    item: some item
    comments: comments
  - store: "[[another store]]"
    item: another item
    comments: other comments
---

```

A1:

Another Example: A1_11 (Before using FLATTEN)

NOTE:
Before running FLATTEN purchases AS OnePurchase, the field purchases in the page, is an AoH as shown below.

  • Here is a slice of the page hash, where the page.file.name is dic_19920301.
```JSON
{
    date: "1992-03-01T00:00:00.000Z",
    purchases: [
        {
            store: "[[some store]]",
            item: "some item",
            comments: "comments",
        },
        {
            store: "[[another store]]",
            item: "another item",
            comments: "other comments",
        },
    ],
}
```

Another Example: A1_12 (After using FLATTEN)

NOTE:
After running FLATTEN purchases AS OnePurchase, the OnePurchase in the page is a Hash as shown below.

  • Here is a slice of the page hash, where the page.file.name is dic_19920301.
```JSON
[
    {
        date: "1992-03-01T00:00:00.000Z",
        OnePurchase: {
            store: "[[some store]]",
            item: "some item",
            comments: "comments",
        },
        purchases: [
            {
                store: "[[some store]]",
                item: "some item",
                comments: "comments",
            },
            {
                store: "[[another store]]",
                item: "another item",
                comments: "other comments",
            },
        ],
    },
    {
        date: "1992-03-01T00:00:00.000Z",
        OnePurchase: {
            store: "[[another store]]",
            item: "another item",
            comments: "other comments",
        },
        purchases: [
            {
                store: "[[some store]]",
                item: "some item",
                comments: "comments",
            },
            {
                store: "[[another store]]",
                item: "another item",
                comments: "other comments",
            },
        ],
    },
]
```

Q2: What is the data structure of the file dic_19920601?

Summary_Q2
Original Example: Q2 (To be explained)

NOTE:

  1. Take the following file dic_19920601 as an example.
  2. The purchases in the page is a Hash.
```yaml
---
date: 1992-06-01
purchases:
  - store: "[[some store]]"
    item: some item
    comments: comments
---

```

A2_21:

Another Example: A2_21
  • Here is a slice of the page hash, where the page.file.name is dic_19920601.
```JSON
{
    date: "1992-06-01T00:00:00.000Z",
    purchases: [
        {
            store: "[[some store]]",
            item: "some item",
            comments: "comments",
        },
    ],
}
```

Test

Summary
  • dataview: v0.5.55

Input

Summary

dictionary files: for the DQL10

  • Location: “100_Project/02_dataview/Q17_Purchases/Q17_test_data”

folder: 03_an_AoH_consists_of_two_hashes

  • filename : dic_19920301
---
date: 1992-03-01
purchases:
  - store: "[[some store]]"
    item: some item
    comments: comments
  - store: "[[another store]]"
    item: another item
    comments: other comments
---



folder: 04

  • filename : dic_19920401
---
date: 1992-04-01
purchases:
  - store: "[[some store]]"
    item: apples
    comments: 
  - store: "[[some store]]"
    item: oranges
    comments: 
---



folder: 05

  • filename : dic_19920501
---
date: 1992-05-01
purchases:
  - store: "[[another store]]"
    item: potatoes, potatoes
    comments: 
  - store: "[[another store]]"
    item: a very big watermelon
    comments: 
---



folder: 06_an_AoH_consists_of_one_hash

  • filename : dic_19920601
---
date: 1992-06-01
purchases:
  - store: "[[some store]]"
    item: some item
    comments: comments
---



folder: 07_an_AoH_contains_one_empty_hash

  • filename : dic_19920701
---
date: 1992-07-01
purchases:
  - store: "[[some store]]"
    item: some item
    comments: comments
  - store: 
    item: 
    comments: 
---



folder: 08_null

  • filename : dic_19920801
---
date: 1992-08-01
purchases:
  - store: 
    item: 
    comments: 
---

  • filename : dic_19920806
---
date: 1992-08-06
purchases:
---


folder: 09_undefined

  • filename : dic_19920901
---
date: 1992-09-01

---



folder: 10_excluding_store_not_link

  • filename : dic_19921001
---
date: 1992-10-01
purchases:
  - store: "another store"
    item: another item
    comments: comments
---



DQL10_filter_by_filename_of_a_link_and_TABLE: case_YAML_Y-YYY

Summary

Main DQL

Code Name Data type Group By Purposes Remark
DQL10
_filter_by_filename
_of_a_link
_and_TABLE
OnePurchase.store:
a link
no 1.To filter by purchases
2.To split up a list purchases into each individual element OnePurchase

3.To filter by OnePurchase and OnePurchase.store
4.To define a field variable s_filename_of_link
5.To filter by s_filename_of_link
6.To sort by date in descending order
7.To display the result as a table
NOTE:
Require the files with the case_YAML_Y-YYY structure

The Regular Expression in the DQL10 is based on the DQL10 in the following topic.
- Solutions: by Justdoitcc

Code DQL10_filter_by_filename_of_a_link_and_TABLE: case_YAML_Y-YYY

Summary_code
title: DQL10_filter_by_filename_of_a_link_and_TABLE =>0.Require the files with the `case_YAML_Y-YYY` structure 1.To filter by `purchases` 2.To split up a list `purchases` into each individual element `OnePurchase` 3.To filter by `OnePurchase` and `OnePurchase.store` 4.To define a field variable `s_filename_of_link` 5.To filter by `s_filename_of_link` 6.To sort by `date` in descending order 7.To display the result as a table
collapse: close
icon: 
color: 
```dataview
TABLE WITHOUT ID 
      file.link AS "File",
	    OnePurchase.store AS "store",
	    OnePurchase.item AS "item",
	    OnePurchase.comments AS "comments",
      s_filename_of_link AS "filename_of_store"
      
FROM "100_Project/02_dataview/Q17_Purchases/Q17_test_data"
WHERE purchases       


FLATTEN purchases AS OnePurchase


WHERE OnePurchase AND OnePurchase.store
FLATTEN regexreplace(meta(OnePurchase.store).path, "^(.*/)(.+)(\.md)$", "$2") AS s_filename_of_link
WHERE contains(s_filename_of_link, "another store")
SORT date DESC
```

Screenshots(DQL10)



Reference

Summary

Q88_Links:Regular Expressions

```dataview

FLATTEN regexreplace(meta(up).path, "^(.*/)(.+)(\.md)$", "$2") AS s_filename_of_link 

```

YAML to JSON converters

YAML Formatters


Oh! I didn’t know this is possible!
That’s why I developed my plugin “Table to CSV Exporter”. :wink:

1 Like

I just started using Obsidian a few days ago as a daily journal and finally got my first dataviewjs query working this morning!

It’s nothing too fancy, especially compared to the query in the OP of this thread, but I just wanted to share my little success. My query creates a table of people mentioned in my daily notes, sorted by most recent mention, a count of mentions, and shows me their relationship to me (friend, family, work).

The thing that made this a bit complicated to setup (for me as a newbie) was that I wanted it be completely automatic and not require any manual editing of YAML. I initially had a field in each person’s note that I would have had to update with the date of our last meetup, but instead I found a way to get the latest daily note and use that as the date.

I also originally had a field for relationship, but since I already had everything set up in folders I figured that there might be a way to inherit that directly from the folder structure, and there was.

So here is what the end result looks like…

In my fault I have a folder called “People” and sub-folders in it that have an individual note for every person like this:

image

And my query gives me this table:

// Get the latest daily note mentioning this person. Daily notes must be named so that most recent is latest alphabetically.
function latestDailyNote(k) {
	let notes = k.file.inlinks;
	notes = notes.map(n => dv.page(n));
	notes = notes.where(n => n.file.folder == "Daily Journal");
	notes = notes.map(n => n.file.name);
	notes = notes.sort(n => n,'desc');
	return notes[0];
}

dv.table(["Name", "Relationship", "Mentions", "Last Mention"], dv.pages('"People"')
	.where(p => !p.file.link.equals(dv.current().file.link)) // Must use equals(), == fails because not both strings?
	.sort(p => latestDailyNote(p), 'desc')
    .map(p => [
	    p.file.link, 
	    p.file.folder.split("/")[p.file.folder.split("/").length-1],
	    p.file.inlinks.length, 
	    latestDailyNote(p)]))

I’ve probably written this in an unnecessarily convoluted way as I have zero experience in javascript. I’m just happy that the thing actually works, but would welcome any improvements, especially ones that might make it more efficient.

One thing that caused me a lot of problems in particular was working with links. It seems that links don’t necessary sort by the text of the link. Does anyone know how an array of links is sorted? In the end I settled for using dv.page to get the page of the link and then file.name to get the text of the link and sorting on that.

4 Likes

I’m trying to do a dv.table without the counts in the headers.

Anyone has an idea how to do so? I’m seeing

https://github.com/blacksmithgu/obsidian-dataview/search?q=values.length

and it appears there is no configuration option. At the same time, I see many people posting screenshots of examples where there are no counters in the headers.

See here:

Generated like this:

---
title: Meetings
days: -10
---

# Upcoming Meetings

```dataviewjs
Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

function sortDate(a, b) {
	return new Date(a) < new Date(b);
}

function padTo2Digits(num) {
  return num.toString().padStart(2, '0');
}

function formatDate(date) {
	date.setHours(0, 0, 0, 0);
  return [
    date.getFullYear(),
    padTo2Digits(date.getMonth() + 1),
    padTo2Digits(date.getDate()),
  ].join('-');
}

let pg = dv.current(); 

let pages = dv.pages("#meeting")
	.where(p =>
		   p.date
		&& p.file.name != pg.file.name
		&& new Date().addDays(pg.days) <= new Date(p.date)
	)
	.sort(p => p.date, "desc", sortDate)
;

for (let group of pages.groupBy(
			b => formatDate(new Date(b.date))
		)
	) { 
	dv.table(
		  [group.key, "Meeting"],
			group.rows
			  .map(k => [ k.date, k.file.link ] 
			) 
		); 
}

I’m sure this is stupidly easy question but I’m a javascript novice and I’ve been working an (unrelated) update all night. Googling skills haven’t helped, so can someone assist?

I have an inline dataviewjs script and all I want to do is a case-insensitive string compare. In straight dataview I’ve been doing this: WHERE contains(lower(muddle),“blarg”)

where ‘muddle’ is defined in YAML.

In my inline dataviewjs script I have .where( k => k.muddle == “blarg”) which works as long as the case fully matches but I haven’t been able to force ‘k.muddle’ to lowercase. toLowerCase, lower, etc. have been tried as a result of google searches.

Trying to get some magic with Dashboard++…

Help? Thanks!

Topic

Summary
  • How to hide the file count in the_nth_of_table dataview table?
  • How to hide the file count in each dataview table?

Using DVJS

Summary_DVJS

Hide the file count in the the_nth_of_table dataview table

```JS
// M91. hide the file count in the `the_nth_of_table` dataview table :
// #####################################################################
let the_nth_of_table = 2;
this.container.querySelectorAll(
    ".table-view-table tr:first-of-type th:first-of-type > span.small-text"
)[the_nth_of_table - 1].style.visibility = "hidden";
```

Hide the file count in each dataview table

```JS
// M99. hide the file count in each dataview table :
// #####################################################################
let css_Lists = this.container.querySelectorAll(
    ".table-view-table tr:first-of-type th:first-of-type > span.small-text"
);
for (let i = 0; i < css_Lists.length; i++) {
    css_Lists[i].style.visibility = "hidden";
}
```

Using CSS snippet

Summary_CSS
```CSS
// C99. hide the file count in each dataview table :
// #####################################################################
.dataview.small-text {
  display: none;
}
```

Reference

Summary

Topic

Summary
  • How to use dv.func.contains in a case-sensitive string comparison?
  • How to use dv.func.icontains in a case-insensitive string comparison?

Test

Summary
  • dataview: v0.5.46

Input

Summary

dictionary files:

  • Location: “100_Project/01_dataviewjs/01_by_example/Q84_Contains/Q84_test_data”

folder: 03

  • filename : dic_19850301
---
Date: 1985-03-01
muddle: BLARG123 abc
---


folder: 04

  • filename : dic_19850401
---
Date: 1985-04-01
muddle: BLARG abc
---


folder: 05

  • filename : dic_19850501
---
Date: 1985-05-01
muddle: blarg456 abc
---


folder: 06

  • filename : dic_19850601
---
Date: 1985-06-01
muddle: blarg abc
---


DVJS10_icontains_and_TABLE

Summary

Main DVJS

Code Name Data type Group By Purposes Remark
DVJS10_icontains_and_TABLE muddle:
a string
no 1.To filter by muddle(An existence check)
2.To filter by muddle(case-insensitive)
3.To display the result as a table

Notes

Summary

The same codes:

  • To filter by muddle(case-insensitive)
Original Example10: DVJS
```JS
.where((page) => dv.func.contains(page.muddle.toLowerCase(), "blarg"))
```
Another Example11: DVJS
```JS
.where((page) => dv.func.contains(dv.func.lower(page.muddle), "blarg"))
```
Another Example12: DVJS
```JS
.where((page) => dv.func.icontains(page.muddle, "blarg")) 
```
Another Example21: DQL
```SQL
WHERE contains(lower(muddle), "blarg")
```
Another Example22: DQL
```SQL
WHERE icontains(muddle, "blarg")
```

Code DVJS10_icontains_and_TABLE

Summary_code
title: DVJS10_icontains_and_TABLE =>1.To filter by muddle(An existence check) 2.To filter by muddle(case-insensitive) 3.To display the result as a table
collapse: close
icon: 
color: 
```dataviewjs
// M11. define pages: gather relevant pages
// #####################################################################
let pages = dv
    .pages(
        '"100_Project/01_dataviewjs/01_by_example/Q84_Contains/Q84_test_data"'
    )
    .where((page) => page.muddle)
    .where((page) => dv.func.contains(page.muddle.toLowerCase(), "blarg"));
    //.sort((page) => page.file.name, "desc");


// M31.Output :
// #####################################################################
//dv.header(2, "pp"); //org
dv.table(
    ["File", "muddle"],
    pages.map((page) => [page.file.link, page.muddle])
);





Screenshots(DVJS10):


2 Likes

Thanks! That solved it. I can see I’m going to need a JavaScript course. Most of my coding was 10+ years ago and in C, C++ or Perl 5. Rust, so much rust…

2 Likes