rethinkDB: get first key name in an object - javascript

I'm just starting with rethinkDB query lang and don't understand how to select the first key (name).
In this case I would be the object notes.
I did it with Object.keys(t)[0]; tries that just returns me args, what am I doing wrong?
{
id: "mission#0",
info:
"Tokyo",
**//how to get the value of content ?**
note: {
"note#032b8836-f647-4165-9ec9-fc22769f3ffa": {
content: "hello world",
context: "all",
glyphId: "glyph#default",
id: "note#032b8836-f647-4165-9ec9-fc22769f3ffa",
meta: {
context: null,
createdAt: 1624044683953,
id: "note#032b8836-f647-4165-9ec9-fc22769f3ffa",
links: null,
parentEntity: "mission#0b1cd61d-bb36-4cf8-8f3d-9cc9b14ff054",
references: { glyphId: "glyph" },
rootAggregateId: "mission#0b1cd61d-bb36-4cf8-8f3d-9cc9b14ff054",
rootAggregatePath: [
"private",
"notes",
"note#032b8836-f647-4165-9ec9-fc22769f3ffa",
],
status: "published",
summaries: {
description: "hello world",
glyph: "bookmark",
glyphColor: "base",
info: "hello world",
},
type: "note",
values: null,
version: 0,
},
},
}
function* extract(next) {
const q = r
.db("test")
.table("mission")
.getAll(true, { index: "recurrenceEnabled" })
.filter((mission) => mission("meta")("status").eq("published"))
.map((m) => {
let t = m("private")("notes");
let p = Object.keys(t)[0];
return {
note: t,
id: m("id"),
info: m("meta")("summaries")("info"),
};
});
return yield q.run(con, next);
}
Thank you for the reading !

Related

Node 'Flatten/Merge' Array of Objects Containing Arrays and Display with forEach in EJS

Apologies for any repeats here, please point me in the direction of a solution if one exists.
Any other time, I seem able to display array data in ejs no problem, but this new flatten function has me stumped.
I have a nested array:
var array =
[{
page: {
results: [{
id: "1234",
type: "page",
title: "Deprecated Spec",
children: {
page: {
results: [{
id: "5678",
type: "page",
title: "Deprecated | Cash Spec"
},
{
id: "9101",
type: "page",
title: "Deprecated | Ledger Spec",
}
],
},
},
},
{
id: "1121",
type: "page",
title: "Work Spec"
}
]
}
}];
And I have a flatten function:
function flatten(arr) {
let flattened = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flattened = flattened.concat(flatten(arr[i]));
} else {
flattened.push(arr[i]);
}
}
return flattened;
}
I set a const and console.log:
const newArr = (flatten(array))
console.log(newArr);
In the terminal I receive: [ { page: { results: [Array] } } ]
For what it's worth, I've also tried flattening this nested array with these methods, and both return the same results.
const newArr2 = Array.prototype.concat.apply([], array);
const newArr3 = array.flat();
Hmm ok, I figure I can forEach and display the data on the .ejs page, which is set as:
<% newArr.forEach(function (newArr){ %>
<%= newArr.title %>
<% }) %>
But this shows nothing.
I have the res.render functioning properly as I am able to send and display other arrays/data sets.
If I try to "get into the array" with something like this: newArr[0].page.results, or any other variances, they don't work.
What am I missing to see my flattened array (using the recursive function) in both the console.log and on my ejs page?
UPDATED:
Per comments below, here is my desired output for the arrays and objects seen in var array:
[{
page: {
results: [
{
id: "1234",
type: "page",
title: "Deprecated Spec"
},
{
id: "5678",
type: "page",
title: "Deprecated | Cash Spec"
},
{
id: "9101",
type: "page",
title: "Deprecated | Ledger Spec"
},
{
id: "1121",
type: "page",
title: "Work Spec"
}
]
}
}];
Here is a pic of my current console.log
Many Thanks!
You should adapt your code to flatten the array like this to achieve the desired output:
const array = [
{
page: {
results: [
{
id: '1234',
type: 'page',
title: 'Deprecated Spec',
children: {
page: {
results: [
{
id: '5678',
type: 'page',
title: 'Deprecated | Cash Spec',
},
{
id: '9101',
type: 'page',
title: 'Deprecated | Ledger Spec',
},
],
},
},
},
{
id: '1121',
type: 'page',
title: 'Work Spec',
},
],
},
},
]
function flatten(arr) {
const flattened = []
for (const { children, ...element } of arr) {
flattened.push(element)
if (children) {
flattened.push(...flatten(children.page.results))
}
}
return flattened
}
const flat = [{ page: { results: flatten(array[0].page.results) } }]
console.log(flat)
console.log(flat[0].page.results)
// [
// {
// "page": {
// "results": [
// {
// "id": "1234",
// "type": "page",
// "title": "Deprecated Spec"
// },
// {
// "id": "5678",
// "type": "page",
// "title": "Deprecated | Cash Spec"
// },
// {
// "id": "9101",
// "type": "page",
// "title": "Deprecated | Ledger Spec"
// },
// {
// "id": "1121",
// "type": "page",
// "title": "Work Spec"
// }
// ]
// }
// }
// ]

Converting an array to an object of nested objects for a tree diagram in Javascript

i'm attempting to create a Tree Diagram with react-d3-js. It needs to be in a specific format. So i need to convert the initial data that i have to the format.
This is a diagram for a shop to see the distribution chain and who is allowed to make a purchase from specific nodes.
Initial Data:
store.name = 'Absolut Chocolat' //Main Parent
store.shopconditions: [
{
"role": "agent",
"condition": ["owner", "stokist"]
},
{
"role": "stokist",
"condition": ["owner", "master stokist"]
},
{
"role": "master stokist",
"condition": ["owner"]
}
]
// If role is agent, then they are allowed to buy from 'owner' and 'stokist'
Here's the hardcoded ideal output:
orgChart = {
name: 'Absolut Chocolat',
children: [
{ name: 'Agent' },
{
name: 'Stokist',
children: [
{
name: 'Agent',
},
],
},
{
name: 'Master Stokist',
children: [
{
name: 'Stokist',
children: [
{
name: 'Agent',
},
],
},
],
},
],
};
With a few for each loops, i've gotten to the first 2 layers of the intended output but i cannot find a way to get more than that.
Here is what i got so far:
Agent node is not under Master Stokist
Current code:
let chartData = { name: store.name, children: [] };
store.shopconditions.forEach((i) => {
i.condition.forEach((c) => {
if (c === 'owner') {
chartData.children.push({ name: i.role });
}
});
});
const chartDataParser = (data) => {
data.children.map((i) => {
for (const [k, v] of Object.entries(i)) {
store.shopconditions.forEach((c) => {
c.condition.forEach((o) => {
if (o === v) {
if (!i.children) {
i.children = [{ name: c.role }];
} else {
i.children.push({ name: c.role });
}
}
});
});
}
});
};
chartDataParser(chartData);
Current output:
{
name: 'Absolut Chocolat',
children: [
{ name: 'Agent' },
{
name: 'Stokist',
children: [
{
name: 'Agent',
},
],
},
{
name: 'Master Stokist',
children: [
{
name: 'Stokist',
// Missing children: Agent Node
},
],
},
],
};
What the tree diagram should look like:
As you can see under Master Stokist node, Agent is under Stokist
The Agent node is not reached under the stokist node in the right most chain. I need a fix to my current code so it can go to that extra layer. Thanks in advance. Looking forward to learn from your answers.
You can build an object that lists children by role and then use that to recursively build the nodes of the object. Possibly something like the following:
const store = {
name: 'Absolut Chocolat',
shopconditions: [
{ "role": "agent", "condition": ["owner", "stokist"], name: 'Agent' },
{ "role": "stokist", "condition": ["owner", "master stokist"], name: 'Stockist' },
{ "role": "master stokist", "condition": ["owner"], name: 'Master Stockist' },
]
};
const build_role_map = (store) => {
let role_map = Object.fromEntries(
store.shopconditions.map((v) => [v.role, { ...v, children: [] }])
);
role_map.owner = { "role": "owner", "condition": [], children: [], name: store.name };
store.shopconditions.forEach(
({ role, condition }) => {
condition.forEach((parent) => { role_map[parent].children.push(role) })
}
);
return role_map;
};
const build_node = (role_map, { name, children }) => {
let node = { name };
if(children.length > 0)
node.children = children.map((child) => build_node(role_map, role_map[child]));
return node;
};
const build_tree = (store) => {
const role_map = build_role_map(store);
return build_node(role_map, role_map.owner);
};
console.log(build_tree(store));

react TypeError: Cannot read property 'type1' of undefined

I'm studying the react-beautiful-dnd example, and I want to add a conditional repulsion of an element, but I get an error that the field cannot be read.
This data
const initialData = {
tasks: {
'task-1': { id: 'task-1', content: 'Take out the garbage',type1: 'w' },
'task-2': { id: 'task-2', content: 'Watch my favorite show',type1: 'a' },
'task-3': { id: 'task-3', content: 'Charge my phone',type1: 'h' },
'task-4': { id: 'task-4', content: 'Cook dinner',type1: 'w' }
},
columns: {
'column-1': {
id: 'column-1',
title: 'To do',
type2: 'all',
taskIds: ['task-1', 'task-2', 'task-3', 'task-4']
},
'column-2': {
id: 'column-2',
title: 'In progress',
type2: 'w',
taskIds: []
},
'column-3': {
id: 'column-3',
title: 'Done',
type2: 'a',
taskIds: []
}
},
// Facilitate reordering of the columns
columnOrder: ['column-1', 'column-2', 'column-3'] }export default initialData
so they are connected
import initialData from './initial-data'
so it is assigned in state
state = initialData
this is how it is used and everything that I described it works and this is the code from the example
const start = this.state.columns[source.droppableId]
const finish = this.state.columns[destination.droppableId]
if (start === finish) {
const newTaskIds = Array.from(start.taskIds)
now below i want to add my condition and it throws an error
const typeDrag = this.state.tasks[source.draggableId]
const typeDrop = this.state.columns[destination.droppableId]
if(typeDrag.type1!==typeDrop.type2)
{return}
and I don't understand why start.taskIds works, but typeDrag.type1 reports that there is no such field
similarly executable codesandbox example
example
Solution:
instead of: const typeDrag = this.state.tasks[source.draggableId]
use: const typeDrag = this.state.tasks[draggableId]
Explanation:
In your code source doesn't have property draggableId.
So typeDrag is undefined because source.draggableId is undefined.
Argument of your onDragEnd hook looks like that:
{
"draggableId": "task-2",
"type": "TASK",
"source": {
"index": 1,
"droppableId": "column-1"
},
"destination": {
"droppableId": "column-2",
"index": 0
},
"reason": "DROP"
}
By checking your sandbox sample I see that you've already extracted draggableId property to a constant from the method argument ("result"):
const { destination, source, draggableId } = result; // line:28
So using draggableId instead of source.draggableId resolves TypeError: Cannot read property 'type1' of undefined.

how to format an object of array to a new one

I'm trying to transform an object contain array to another one with javascript. Below is an example of the object field and what the formatted one should look like.
The data after formating must show me only fileds who has the "ABS" in funcName
let beforeData = {
SUMMER: [
{ funcName: '{{WORKING_ABS}}', subject: { en: "Exercice1"} },
{ funcName: '{{PULLS_BODY}}', subject: { en: "Exercice2"} },
],
WINTER: [
{ funcName: '{{FULL_BODY}}', subject: { en: "Exercice3"} },
{ funcName: '{{REST_ABS}}', subject: { en: "Exercice4"} },
]
};
I need The object to be exactly like this one
let AfterData ={
worklinks: [
{
name: 'Exercice1',
link: '{{WORKING_ABS}}',
},
{
name: 'Exercice4',
link: '{{REST_ABS}}',
},
]
},
I was trying to make a method like this one (Its just a draft ) , maybe somone will help to improve this method
export const functTransform = (dataaas) => { Object.keys(dataaas).map(fiels => ({
worklinks =>funcName.search("ABS") > -1).map(({funcName, subject}) => ({
link: funcName,
name: subject.en
}))};
I'm new working with javascript so any help is greatly appreciated, Thanks.
Consider following code:
const beforeData = {
SUMMER: [
{ funcName: '{{WORKING_ABS}}', subject: { en: "Exercice1"} },
{ funcName: '{{PULLS_BODY}}', subject: { en: "Exercice2"} },
],
WINTER: [
{ funcName: '{{FULL_BODY}}', subject: { en: "Exercice3"} },
{ funcName: '{{REST_ABS}}', subject: { en: "Exercice4"} },
]
};
const isABS = (str) => str.indexOf('ABS') > -1;
const result = Object.values(beforeData).flat().map(o => ({link: o.funcName, name: o.subject.en})).filter(o => isABS(o.link));
console.log(result);
You could do it like this? (Reduce with forEach)
let beforeData = {
SUMMER: [
{ funcName: '{{WORKING_ABS}}', subject: { en: "Exercice1"} },
{ funcName: '{{PULLS_BODY}}', subject: { en: "Exercice2"} },
],
WINTER: [
{ funcName: '{{FULL_BODY}}', subject: { en: "Exercice3"} },
{ funcName: '{{REST_ABS}}', subject: { en: "Exercice4"} },
]
};
function transform(inputData, funcComparator){
if (funcComparator == undefined){
funcComparator = (item) => item.funcName.includes("ABS");
}
return Object.values(inputData).reduce((aggArr, arr) => {
arr.forEach(item => {
if (funcComparator(item)){
const itemCopy = {name: item.subject.en, link: item.funcName};
aggArr.push(itemCopy);
}
})
return aggArr;
}, []);
}
//use it to find all your "ABS":
console.log(transform(beforeData));
//another example, use it to find all your "BODY":
//console.log(transform(beforeData, (item) => item.funcName.includes("BODY")));
Output:
[
{
"name": "Exercice1",
"link": "{{WORKING_ABS}}"
},
{
"name": "Exercice4",
"link": "{{REST_ABS}}"
}
]

Create a key map for all paths in a recursive/nested object array

I have an n levels deep nested array of tag objects with title and ID. What I'm trying to create is a an object with IDs as keys and values being an array describing the title-path to that ID.
I'm no master at recursion so my attempt below doesn't exactly provide the result I need.
Here's the original nested tag array:
const tags = [
{
title: 'Wood',
id: 'dkgkeixn',
tags: [
{
title: 'Material',
id: 'ewyherer'
},
{
title: 'Construction',
id: 'cchtfyjf'
}
]
},
{
title: 'Steel',
id: 'drftgycs',
tags: [
{
title: 'Surface',
id: 'sfkstewc',
tags: [
{
title: 'Polished',
id: 'vbraurff'
},
{
title: 'Coated',
id: 'sdusfgsf'
}
]
},
{
title: 'Quality',
id: 'zsasyewe'
}
]
}
]
The output I'm trying to get is this:
{
'dkgkeixn': ['Wood'],
'ewyherer': ['Wood', 'Material'],
'cchtfyjf': ['Wood', 'Construction'],
'drftgycs': ['Steel'],
'sfkstewc': ['Steel', 'Surface'],
'vbraurff': ['Steel', 'Surface', 'Polished'],
'sdusfgsf': ['Steel', 'Surface', 'Coated'],
'zsasyewe': ['Steel', 'Quality']
}
So I'm building this recursive function which is almost doing it's job, but I keep getting the wrong paths in my flat/key map:
function flatMap(tag, acc, pathBefore) {
if (!acc[tag.id]) acc[tag.id] = [...pathBefore];
acc[tag.id].push(tag.title);
if (tag.tags) {
pathBefore.push(tag.title)
tag.tags.forEach(el => flatMap(el, acc, pathBefore))
}
return acc
}
const keyMap = flatMap({ title: 'Root', id: 'root', tags}, {}, []);
console.log("keyMap", keyMap)
I'm trying to get the path until a tag with no tags and then set that path as value for the ID and then push the items 'own' title. But somehow the paths get messed up.
Check this, makePaths arguments are tags, result object and prefixed titles.
const makePaths = (tags, res = {}, prefix = []) => {
tags.forEach(tag => {
const values = [...prefix, tag.title];
Object.assign(res, { [tag.id]: values });
if (tag.tags) {
makePaths(tag.tags, res, values);
}
});
return res;
};
const tags = [
{
title: "Wood",
id: "dkgkeixn",
tags: [
{
title: "Material",
id: "ewyherer"
},
{
title: "Construction",
id: "cchtfyjf"
}
]
},
{
title: "Steel",
id: "drftgycs",
tags: [
{
title: "Surface",
id: "sfkstewc",
tags: [
{
title: "Polished",
id: "vbraurff"
},
{
title: "Coated",
id: "sdusfgsf"
}
]
},
{
title: "Quality",
id: "zsasyewe"
}
]
}
];
console.log(makePaths(tags));

Categories

Resources