how to correctly generate an nested array in vue - javascript

I have a vue application where I am right now getting this kind of an json object:
[
{
"meetingName":"ewq",
"meetingUrl":"",
"meetingPw":"",
"date":"2021-05-30",
"times":[
{
"startTime":"15:30",
"endTime":"16:30"
},
{
"startTime":"17:30",
"endTime":"18:30"
}
]
},
{
"meetingName":"ewq",
"meetingUrl":"",
"meetingPw":"",
"date":"2021-05-31",
"times":[
{
"startTime":"15:30",
"endTime":"16:30"
}
]
}
]
But I am aiming for something like this:
{
"meetingName":"Test",
"meetingPw":"test22",
"meetingUrl":"localhost",
"meetingTimes":[
{
"date":"15.12.2020",
"times":[{
"startTime":"15:00",
"endTime":"16:00"
}]
},
{
"date":"25.12.2020",
"times":[
{
"startTime":"17:00",
"endTime":"18:00"
},
{
"startTime":"19:00",
"endTime":"2:00"
}
]
}
]
}
But I just cant change it to get like this in my code, could someone look at my code and tell me where my mistake is?
<script>
import DatePickerComponent from "#/components/DatePickerComponent";
export default {
name: "GenerateMeetingSettings",
data: () => ({
selectedTime: [],
dates: new Date().toISOString().substr(0,10),
datesFinal: [],
meetingSettingUrl: "",
meetingPW: "",
generatedLink: false,
meetingName: "",
dialog: false,
menu: false,
modal: false,
menu2: false,
menu3: false
}),
methods:{
addTimeFields(){
this.selectedTime.push({
startTime:"",
endTime: "",
})
},
saveDateAndTIme(e) {
this.datesFinal.push({
meetingName: this.meetingName,
meetingUrl: this.meetingSettingUrl,
meetingPw: this.meetingPW,
date: this.dates,
times: this.selectedTime
}
)
this.selectedTime = [];
},
generateMeetingLink(){
let meetinId = this.meetingName
console.log(this.meetingName)
this.meetingSettingUrl = "http://localhost:8080/" + meetinId
this.generatedLink = true
console.log(JSON.stringify(this.datesFinal))
}
}
I just posted the script part as there the logic happens for the array which is generated

this is the solution I could find:
<script>
import DatePickerComponent from "#/components/DatePickerComponent";
export default {
name: "GenerateMeetingSettings",
data: () => ({
selectedTime: [],
finalMeeting: [],
datesFinal: [{meetingName: "",
meetingTime: []}] ,
dates: new Date().toISOString().substr(0,10)})
,
methods:{
addTimeFields(){
this.selectedTime.push({
date: this.dates,
startTime:"",
endTime: "",
})
},
saveDateAndTIme(e) {
this.datesFinal[0].meetingTime.push(this.selectedTime),
this.selectedTime = []
},

Related

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));

rethinkDB: get first key name in an object

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 !

Filter nested array in object javascript express

Considering the below object:
[
{
id: 5fc0be2990a8a12cc0ba0b5c,
projectName: 'E-271120-B',
projectManagaer: '5f7f1ba973ff621da4322248',
dataInici: 2020-11-26T23:00:00.000Z,
dataEntrega: 2020-11-26T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-11-27T08:51:57.242Z,
updated: 2021-01-25T10:01:18.733Z
tabs: [{permissionsUserID:[250,8]},{permissionsUserID:[3]}],
__v: 3
},
{
tabs: [{permissionsUserID:[3,350]},{permissionsUserID:[15]}],
_id: 5fc0be4690a8a12cc0ba0b5f,
projectManagaer: '5f7f0e69b5862e1a085db388',
projectName: 'E-271120-C',
dataInici: 2020-11-27T23:00:00.000Z,
dataEntrega: 2020-11-29T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-01-21T08:46:41.958Z,
updated: 2021-01-21T08:46:41.958Z,
__v: 2
},
{
tabs: [{permissionsUserID:[31,350]},{permissionsUserID:[8,893]}],
_id: 5fc0be4690a8a12cc0ba0b5f,
projectManagaer: '5f7f0e69b5862e1a085db388',
projectName: 'E-23410-C',
dataInici: 2020-11-27T23:00:00.000Z,
dataEntrega: 2020-11-29T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-01-21T08:46:41.958Z,
updated: 2021-01-21T08:46:41.958Z,
__v: 2
}
]
Each object represents a Project. A project has many tabs.
I want to return only the projects that at least one tab contains in permissionsUserID the ID of the user that is logged.
So if the user that is logged has the ID 8, these are the projects I want to obtain:
[
{
id: 5fc0be2990a8a12cc0ba0b5c,
projectName: 'E-271120-B',
projectManagaer: '5f7f1ba973ff621da4322248',
dataInici: 2020-11-26T23:00:00.000Z,
dataEntrega: 2020-11-26T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-11-27T08:51:57.242Z,
updated: 2021-01-25T10:01:18.733Z
tabs: [{permissionsUserID:[250,8]},{permissionsUserID:[3]}],
__v: 3
},
{
tabs: [{permissionsUserID:[31,350]},{permissionsUserID:[8,893]}],
_id: 5fc0be4690a8a12cc0ba0b5f,
projectManagaer: '5f7f0e69b5862e1a085db388',
projectName: 'E-23410-C',
dataInici: 2020-11-27T23:00:00.000Z,
dataEntrega: 2020-11-29T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-01-21T08:46:41.958Z,
updated: 2021-01-21T08:46:41.958Z,
__v: 2
}
]
That's the filter I have done:
async getAll(pagination, user) {
try {
const filter = {};
if(pagination.archived) {
filter['archived'] = pagination.archived;
}
if(pagination.search) {
filter['$text'] = {$search: pagination.search}
}
const { Project: projectSchema } = this.getSchemas();
const projectsDocs = await projectSchema.paginate(filter, {
limit: pagination.limit ? parseInt(pagination.limit) : 10,
page: pagination.page ? parseInt(pagination.page) + 1 : 1
});
if (!projectsDocs) {
throw new errors.NotFound('No Projects.');
}
projectsDocs.docs.forEach(element => {
element.tabs.filter( d => d.permissionsUserID.every( c => c.includes(user._id)));
});
return projectsDocs;
} catch (error) {
throw error;
}
},
Here is one way
const data = [...];
const userId = 8;
const result = data.filter((item) => {
const {tabs} = item;
let loggedIn = false;
tabs.forEach((tab) => {
if (tab.permissionsUserID.includes(userId)) {
loggedIn = true;
return true
}
})
return loggedIn;
})
Here's a simple function which should get you what you want.
Filter() returns a subset of the projects list. Some() returns true if at least one of the tabs has the value we're looking for. Includes() returns true if the permissionsUserId list has the user id we want. Chain those together and you get the subset of projects where a tab's permissions has the desired user id.
const data = [
/* list of projects */
],
userId = 8;
function getProjectsForUserId (data, userId) {
return data.filter((project) => {
return project.tabs.some((tab) => {
return tab.permissionsUserID.includes(userId);
});
});
}
console.log(getProjectsForUserId(data, 8));

ReactJs- How to do mapping for each list Axios post Method?

I am trying to implement list post api in dynamic form but i can't correctly post data in dynamic form here it is my all code what i did.when i send post request from my form all data display but only prizes list item not showing i tried to use mapping but still i can resolve my issue pleaase guide me where i am doing mistake
import React, { Component } from "react";
import { Helmet } from "react-helmet";
import Form from "./Form";
import Additional from "./Additional";
import Prize from "./Prize";
import Swal from "sweetalert2";
import axios from "axios";
import { withTranslation } from "react-i18next";
class Create extends Component {
constructor(props) {
super(props);
this.state = {
isHidden: true,
title: "",
lead: "",
span: "",
without: "",
startDate: null,
endDate: null,
parameter: "",
prizes: [
{
number_list: [],
prize_type: "",
name: "",
value: null,
quantity: ""
}
]
};
this.handleSubmit = this.handleSubmit.bind(this);
this.onChange = this.onChange.bind(this);
this.toggleHie = this.toggleHie.bind(this);
}
async onChange(event) {
await this.setState({
[event.target.name]: event.target.value
});
console.log(this.state);
}
handleSubmit(e) {
let authToken = localStorage.getItem("Token");
e.preventDefault();
const data = {
title: this.state.title,
lead: this.state.lead,
span: this.state.span,
startDate: this.state.startDate,
endDate: this.state.endDate,
parameter: this.state.parameter,
prizes: [
this.state.prizes.map(c => {
c.number_list = c.number_list;
c.prize_type = c.prize_type;
c.name = c.name;
c.value = c.value;
c.quantity = c.quantity;
})
]
};
axios({
method: "post",
url: `https://digitalfleet.eu/api/1/campaigns/`,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + JSON.parse(authToken)
},
data
})
.then(res => {
this.setState({
title: "",
lead: "",
span: "",
startDate: "",
endDate: "",
parameter: "",
prizes: [
{
number_list: [],
prize_type: "",
name: "",
value: null,
quantity: ""
}
]
});
this.props.history.push("/createcampaign");
Swal.fire({
title: "Campaign",
type: "success",
text: " Added Successfully !",
showConfirmButton: false,
timer: 2000
});
})
.catch(err => {
console.log(err);
Swal.fire({
title: "Campaign",
type: "error",
text: "Error while Creating new!",
timer: 2000
});
});
}
Javascript map returns an array, so you don't need to define data.prizes as array like you did.
Can you construct your data object like this, and try?
const {title, lead, span, startDate, endDate, parameter, prizes} = this.state;
const data = {title, lead, span, startDate, endDate, parameter, prizes};
In your handleSubmit function. Construct the data object like this:
const data = {
title: this.state.title,
lead: this.state.lead,
span: this.state.span,
startDate: this.state.startDate,
endDate: this.state.endDate,
parameter: this.state.parameter,
prizes: [
...this.state.prizes
]
}
Following your current approach, return is missing inside map which might be causing the values to not come. You need to do the following 2 things inorder for code to work. return from map properly and use spread operator otherwise the value will go inside prize[0] instead of prize array.
The code will be:
prizes: [...this.state.prizes.map(c => ({ //Note '(' bracket before '{' for returning object
c.number_list = c.number_list;
c.prize_type = c.prize_type;
c.name = c.name;
c.value = c.value;
c.quantity = c.quantity;
}))]
However, there is simplified version as well, if your data values are equivalent to this.state. You can simply do the following and every other value will sit fine:
data = { ...this.state }
Even for prizes, you can simply do the following:
data = {
...
prizes: [ ...this.state.prizes ]
}
Example snippet demonstrating all of above (including your current approach):
const state = {
title: "title prize",
lead: "lead prize",
span: "span prize",
prizes: [{
prize_type: "type1",
name: "Type 1"
}, {
prize_type: "type2",
name: "Type 2"
}]
}
const data1 = { ...state }
const data2 = {
title: state.title,
lead: state.lead,
span: state.span,
prizes: [...state.prizes]
}
const data3 = {
title: state.title,
lead: state.lead,
span: state.span,
prizes: [...state.prizes.map(c => ({
prize_type: c.prize_type,
name: c.name,
}))]
}
console.log(data1)
console.log(data2)
console.log("Your approach")
console.log(data3)
.as-console-wrapper {
top: 0;
max-height: 250px !important;
}
you can directly use this
const {title, lead, span, startDate, endDate, parameter, prizes} = this.state;
const data = { title, lead, span, startDate, endDate, parameter, prizes }

vue.js push array component

1.vue.js problem component
i want insert a new message in new array with method on click event but
not work for me because function is incomplete
where is the problem.
help me please.
<div class="col-lg-12">
<h1>{{message.title}}</h1>
<h4>{{message.subtitle}}</h4>
</p> {{message.body}}</p>
<button v-on:click="newMessage">Reverse Message</button>
</div>
import {
VueTabs,
VTab
}
from "vue-nav-tabs";
import "vue-nav-tabs/themes/vue-tabs.css";
export default {
components: {
VueTabs,
VTab
},
data() {
return {
title: "elenco",
messages: [{
id: 1,
title: "titolo",
subtitle: "sottotitolo",
body: "argomento",
author: "Amedeo",
date: "17/07/2017",
files: [{
id: 1,
title: "Allegatoriunione",
openfile: "Allegato.pdf"
}, ],
methods: {
newMessage: function() {
this.message.title = this.message.title
.push("")
.split("")
.reverse()
.join("");
}
Your Code Contains many syntax errors which probably fails silently.
Try this new updated code:
<script>
import { VueTabs, VTab } from 'vue-nav-tabs'
import 'vue-nav-tabs/themes/vue-tabs.css'
export default {
components: { VueTabs, VTab },
data() {
return {
title: 'elenco',
messages: [
{
id: 1,
title: 'titolo',
subtitle: 'sottotitolo',
body: 'argomento',
author: 'Amedeo',
date: '17/07/2017',
files: [
{
id: 1,
title: 'Allegatoriunione',
openfile: 'Allegato.pdf'
}
]
}
]
}
},
methods: {
newMessage() {
this.message.title = this.message.title
.push('')
.split('')
.reverse()
.join('')
}
}
}
</script>

Categories

Resources