Map object with array in javascript - javascript

I'm using Vue Select Image for multi selecting images. Vue Select Image expects the array to be with the following keys
[{
id: '1',
src: 'https://unsplash.it/200?random',
alt: 'Alt Image 1'
}, {
id: '2',
src: 'https://unsplash.it/200?random',
alt: 'Alt Image 2'
}]
And my api route gives the object with following keys:
(2)[{…}, {…}]
0:
created_at: "2019-07-26 07:44:56"
id: 3
name: null
path: "img/d1ef5a9c54ee32df12c213b1491e1636.jpg"
thumb: "img/thumb_d1ef5a9c54ee32df12c213b1491e1636.jpg"
updated_at: "2019-07-26 07:44:56"
Below is my code snippet:
import VueSelectImage from "vue-select-image";
import "vue-select-image/dist/vue-select-image.css";
export default {
data() {
return {
dataImages: [{
id: "",
src: "",
alt: ""
}]
},
selected: {},
initialLoad() {
axios.get("api/gallery").then(response => {
this.dataImages = Object.keys(response.data.data).map(function(key) {
return [Number(key), response.data.data[key]];
});
// console.log(response.data.data);
});
},
components: {
VueSelectImage
},
};
<template>
<div>
<vue-select-image :dataImages="dataImages" #onselectimage="selected"></vue-select-image>
</div>
</template>
The above code maps object with array with its own keys. And displays 2 circle as there are 2 data receiving from api. Clicking on them gives the following error:
Error in event handler for "onselectimage": "TypeError: fns.apply is not a function"

Map through array of objects you get from API, it returns new array with objects with desired fields.
axios.get("api/gallery").then(response => {
this.dataImages = response.data.data.map((obj, index) => {
return {
id: obj.id,
src: obj.path,
alt: `Alt image ${index}`
};
});
});

Related

JS says an object is undefined even though it shows with console.log

As the title states, my JS says an object is undefined even though if I console.log the parent it shows. I'm using prisma, but all that does is return a list of the objects containing {id, title, user:{id, name}}.
Code:
const userProjects = await prisma.projectMembers.findMany({
where: {
userId: token._id
},
select: {
project: {
select: {
id: true,
title: true,
user: {
select: {
id: true,
name: true,
},
},
},
},
},
});
userProjects.map(project => {
console.log(project)
console.log(project.user)
return {
id: project.id,
title: project.title,
user: project.user.id,
}
})
Output:
As you can see in the screenshot, there's a nested project property, and the user property is inside that. So project.user should be project.project.user.
userProjects.map(project => {
console.log(project)
console.log(project.project.user)
return project.project;
})
There's no need for you to create your own object when returning, since it's the same as project.project.

Adding element inside nested array in mongoose

Server Started at Port 3000...
{
_id: new ObjectId("61c707e9f4ff040a47d27c3f"),
username: 'adityaaryam',
password: '1234',
nameOfUser: 'Aditya Aryam',
emailOfUser: 'adityaaryam#gmail.com',
userAllLists: [
{
name: 'Hello',
items: [],
_id: new ObjectId("61c70d915448262d1dca1a69")
},
{
name: 'Work',
items: [],
_id: new ObjectId("61c70d965448262d1dca1a70")
},
{
name: 'Home Work',
items: [],
_id: new ObjectId("61c70d9b5448262d1dca1a79")
},
{
name: 'Hello',
items: [],
_id: new ObjectId("61c70e7f5448262d1dca1a84")
},
{
name: 'Play',
items: [],
_id: new ObjectId("61c7126a5448262d1dca1a9b")
},
{
name: 'Eat',
items: [],
_id: new ObjectId("61c71325b0219e6ce4f57990")
},
{
name: 'Walla',
items: [],
_id: new ObjectId("61c7197de9564390d506cbe9")
}
],
__v: 7
}
This is how my database looks like. I want to push new elements to "items" array which is nested inside the "userAllLists" array using mongoose. How do I implement this?
I have been trying findOneAndUpdate using $push but I am not able to achieve my desriable results.
My Schemas are as follows:
const itemSchema = {
name: String
};
const customListSchema ={
name:String,
items:[itemSchema]
};
const userSchema={
username: String,
password: String,
nameOfUser: String,
emailOfUser: String,
userAllLists: [customListSchema],
};
Thanks in Advance!
I think $push is the right way to push new elements to nested arrays, you didn't show the code you tried to see if it works or not, at all here is an example based on your schema
User.update({_id: "61c707e9f4ff040a47d27c3f", }, {
'$push': {
"userAllLists.$[].items": {name: "test item name"}
}
});
Note: $[] expressions will push the specified object inside all items arrays that exist in userAllLists
To push the item for only specific userAllLists object you can use the following syntax
User.update({_id: "61c707e9f4ff040a47d27c3f", "usersAllLists._id": "61c70d915448262d1dca1a69"}, {
'$push': {
"userAllLists.$.items": {name: "test item name"}
}
});
this will ensure to push the item object to the specified usersAllLists object which has this id 61c70d915448262d1dca1a69

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.

Using map on array of objects results in a errormessage

I am trying to figure out why this simple code does not work, it feels like I have done exactly the same thing many times before without errors. What have I done wrong?
import React, {useState} from 'react'
import { MenuItem } from '../menu-item/menu-item.component'
import './directory.styles.scss'
export const Directory = () => {
const sections = [
{
title: 'hats',
imageUrl: 'https://i.ibb.co/cvpntL1/hats.png',
id: 1,
linkUrl: 'shop/hats'
},
{
title: 'jackets',
imageUrl: 'https://i.ibb.co/px2tCc3/jackets.png',
id: 2,
linkUrl: 'shop/jackets'
},
{
title: 'sneakers',
imageUrl: 'https://i.ibb.co/0jqHpnp/sneakers.png',
id: 3,
linkUrl: 'shop/sneakers'
},
{
title: 'womens',
imageUrl: 'https://i.ibb.co/GCCdy8t/womens.png',
size: 'large',
id: 4,
linkUrl: 'shop/womens'
},
{
title: 'mens',
imageUrl: 'https://i.ibb.co/R70vBrQ/men.png',
size: 'large',
id: 5,
linkUrl: 'shop/mens'
}
];
return (
<div className="directory-menu">
{sections.map((title, imageUrl, id) => <MenuItem key={id} title={title} imageUrl={imageUrl}/>)}
</div>
)
}
Error Message:
Error: Objects are not valid as a React child (found: object with keys
{title, imageUrl, id, linkUrl}). If you meant to render a collection
of children, use an array instead.
You are not destructuring properly i.e.
.((title, imageUrl, id) =>
should be
.(({title, imageUrl, id}) =>
Check out this post, it's a common React error.
You could also try something like this
Object.entries(sections).map((x)=>
return x.title;
})

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