Update all keys with particular value in OrderMap using immutableJs - javascript-objects

I am trying to find the better way to iterate over all keys using immutableJs.
(Basically, I would like to update all the value in the Map at once.)
Tried by changing tdata.setIn([tdata.keySeq(), "comments"], value =>”new Comment”); setIn , UpdateIn - Deep Persistent Change methods in Immutable
let data = [
{
id: "1",
isSelected: false,
isStarred: false,
comments: “comments”,
title: “Title1”,
userName: “uName”
},
{
id: "2",
isSelected: false,
isStarred: false,
comments: “comments”,
title: “Title1”,
userName: “uName”
},
{
id: "3",
isSelected: false,
isStarred: false,
comments: “comments”,
title: “Title1”,
userName: “uName”
},
{
id: "4",
isSelected: false,
isStarred: false,
comments: “comments”,
title: “Title1”,
userName: “uName”
},
{
id: "5",
isSelected: false,
isStarred: false,
comments: “comments”,
title: “Title1”,
userName: “uName”
}
]
let tData = OrderedMap();
for (let i = 0; i < data.length; i++) {
let values = Map(data[i]);
tData = tData.set(data[i].id, values);
}
tdata.updateIn([“2”, "comments"], value =>”new Comment”);
Rather than explicitly specifying key ="2", am looking to update entire Map
Thanks for any help

It sounds like you want to use the map function.
const data = fromJS({
a: {comment: "1"},
b: { comment: "2"},
c: {count: "3"}
);
const newData = data.map((key, value) => {
if (value.get("comment") == "2")
return value.set("comment", "new comment")
else
return value
});

Related

How do I update individual fields in nested objects that are in arrays in MongoDB using Mongoose?

This is my first post so please bear with me. I am building a LinkedIn clone and I am trying to keep track of the work experience, projects and courses of the users, and those will be kept in an array of objects inside of the User schema. Now let's say a user will try to add or update one of the elements in one of those arrays, I have the user ID and I am passing it to findOneAndUpdate() as the filter.
Here is my User schema:
const userSchema = new mongoose.Schema({
user_id: {
type: String,
required: [true, 'User ID required.'],
unique: true,
immutable: true,
},
name: {
type: String,
required: [true, 'Name required.'],
},
email: {
type: String,
required: [true, 'Email required.'],
unique: true,
lowercase: true,
immutable: true,
},
title: {
type: String,
},
location: {
type: String,
},
phone_number: {
type: String,
},
contact_email: {
type: String,
},
photo: {
type: String,
},
website: {
type: String,
},
backdrop: {
type: String,
},
summary: {
type: String,
},
work: {
type: String,
},
connections: {
type: Number,
},
projects: [
{
title: {
type: String,
},
description: {
type: String,
},
start_date: {
type: Date,
},
end_date: {
type: Date,
},
technologies: {
type: String,
},
picture: {
type: String,
},
},
],
skills: [{
skill: {
name: {
type: String,
},
level: {
type: String,
},
},
}],
experience: [
{
company: {
type: String,
},
logo: {
type: String,
},
title: {
type: String,
},
location: {
type: String,
},
start_date: {
type: Date,
},
end_date: {
type: Date,
},
description: {
type: String,
},
},
],
education: [
{
school: {
type: String,
},
logo: {
type: String,
},
degree: {
type: String,
},
location: {
type: String,
},
start_date: {
type: Date,
},
end_date: {
type: Date,
},
description: {
type: String,
},
},
],
languages: [
{
name: {
type: String,
},
level: {
type: String,
},
},
],
awards: [
{
title: {
type: String,
},
date: {
type: Date,
},
awarder: {
type: String,
},
summary: {
type: String,
},
},
],
courses: [
{
title: {
type: String,
},
number: {
type: String,
},
school: {
type: String,
},
start_date: {
type: Date,
},
end_date: {
type: Date,
},
description: {
type: String,
},
},
],
});
And in my UserController.ts file, I tried using this:
const updateUser = async (req: Request, res: Response) => {
try {
const filter = { user_id: req.body.user_id };
const update = req.body;
const updatedUser = await User.findOneAndUpdate(filter, update, {
new: true,
upsert: true,
});
res.status(201).json({
status: 'success',
data: {
user: updatedUser,
},
});
} catch (err) {
res.status(400).json({
status: `ERROR: ${err}`,
message: 'error updating user',
});
}
};
And in my request using the format of the schema but that didn't work out as expected. I know mongoose will automatically give it an _id field to each of the individual objects in the array, but again, I have had no luck updating them. I tried sending a PATCH request with this as the body to add a skill like so:
{
"user_id": "xxxxxxxxxxxxxxxx",
"title": "Mr.",
"skills" : {
"name": "Flute",
"level": "Novice"
}
}
And this was the response I got. It created a skill but didnt add the data in the skill object:
{
"status": "success",
"data": {
"user": {
"_id": "63d3715f2ef9698667230a53",
"user_id": "xxxxxxxxxxxxxxxx",
"name": "Jonathan Abitbol",
"email": "yoniabitbol1#gmail.com",
"projects": [],
"skills": [
{
"_id": "63d4068d2df30c9e943e4608"
}
],
"experience": [],
"education": [],
"languages": [],
"awards": [],
"courses": [],
"__v": 0,
"title": "Mr."
}
}
}
Any help on how to add/edit the nested objects would be appreciated.

How to set state in nested array of objects in ReactJs?

I have this object as a state in reactjs. I want to add another object inside the "childoptions: []" array which is nested inside the options array on button click.
How can I achieve this, pls help...
const [select1, setSelect1] = useState({
id: uuid(),
type: 'select',
properties: {
label: 'Select1',
options: [
// {
// id: uuid(),
// optionName: 'red 🔴',
// value: '',
// childOptions: [],
// },
// {
// id: uuid(),
// optionName: 'green 🟢',
// value: '',
// childOptions: [],
// },
// {
// id: uuid(),
// optionName: 'blue 🔵',
// value: '',
// childOptions: [],
// },
],
},
parentId: null,
});
This is achievable by copy the prevState in the new state with the new object inserted inside the options array.
A more detailed explanation could be found at https://stackoverflow.com/a/26254086/9095807
setSelect1((prevState) => {
return {
...prevState,
properties: {
label: 'Select1',
options: prevState.properties.options.map(obj => obj.id === id ? { ...obj, childOptions: [...obj.childOptions, newChildOptions] } : obj),
}
}
})

How to find and update specific value in nested object array in typescript

I have a nested object array with n level like this:
const data = {
"id": null,
"label": "Locations",
"value": "Locations",
"expanded": true,
"children": [
{
"id": "A978919C-E99C-EB11-8F2E-A01D48E35246",
"value": "Tokyo ",
"label": "Tokyo ",
"checked": true,
"children": [
{
"id": "88887069-179A-EB11-9C25-00163EDCFF95",
"isDefault": true,
"locationId": "A978919C-E99C-EB11-8F2E-A01D48E35246",
"parentsId": null,
"createDate": "2021-06-20T19:03:55.190Z",
"updateDate": "2021-10-16T13:36:41.353Z",
"label": "RAJ - Automotive Japan Fa Fusoh",
"checked": true,
"children": [],
"disabled": false
}
]
},
.
.
]
}
I have an object
{
"id": "A978919C-E99C-EB11-8F2E-A01D48E35246",
"value": "Tokyo ",
"label": "Tokyo ",
"checked": false,
"_depth": 1,
"_id": "A978919C-E99C-EB11-8F2E-A01D48E35246",
"_parent": "rdts1-0",
"_children": [
"88887069-179A-EB11-9C25-00163EDCFF95"
],
"_focused": true
}
and I want to edit checked in the object array by using the IDs in the last object and its children, change each checked in object in the object array to false
I used DFS for the children but I didn't get a good result any help please.
Seems like recursion would suffice:
const data = {
id: null,
label: 'Locations',
value: 'Locations',
expanded: true,
children: [
{
id: 'A978919C-E99C-EB11-8F2E-A01D48E35246',
value: 'Tokyo ',
label: 'Tokyo ',
checked: true,
children: [
{
id: '88887069-179A-EB11-9C25-00163EDCFF95',
isDefault: true,
locationId: 'A978919C-E99C-EB11-8F2E-A01D48E35246',
parentsId: null,
createDate: '2021-06-20T19:03:55.190Z',
updateDate: '2021-10-16T13:36:41.353Z',
label: 'RAJ - Automotive Japan Fa Fusoh',
checked: true,
children: [],
disabled: false,
},
],
},
],
}
function setCheckedToFalse(childrenArr) {
// error handling
if (!Array.isArray(childrenArr)) {
return;
}
childrenArr.forEach((child) => {
// set to false
child.checked = false
// recursion for other children
setCheckedToFalse(child.children)
})
}
setCheckedToFalse(data.children)
console.log(data);
Not sure if I correctly understood the question, but the code below the checked value in the data object is set to false in case it exists in object.
const data = {
id: null,
label: 'Locations',
value: 'Locations',
expanded: true,
children: [
{
id: 'A978919C-E99C-EB11-8F2E-A01D48E35246',
value: 'Tokyo ',
label: 'Tokyo ',
checked: true,
children: [
{
id: '88887069-179A-EB11-9C25-00163EDCFF95',
isDefault: true,
locationId: 'A978919C-E99C-EB11-8F2E-A01D48E35246',
parentsId: null,
createDate: '2021-06-20T19:03:55.190Z',
updateDate: '2021-10-16T13:36:41.353Z',
label: 'RAJ - Automotive Japan Fa Fusoh',
checked: true,
children: [],
disabled: false,
},
],
},
],
};
const object = {
id: 'A978919C-E99C-EB11-8F2E-A01D48E35246',
value: 'Tokyo ',
label: 'Tokyo ',
checked: false,
_depth: 1,
_id: 'A978919C-E99C-EB11-8F2E-A01D48E35246',
_parent: 'rdts1-0',
_children: ['88887069-179A-EB11-9C25-00163EDCFF95'],
_focused: true,
};
// Gets all ids (nested ones included) from object
function getIdsHashMap(obj) {
const idsHashMap = {};
const loopThroughChildren = (children = []) => {
children.forEach((el) => {
idsHashMap[el] = true;
if (el._children) {
loopThroughChildren(el._children);
}
});
};
if (obj.id) {
idsHashMap[obj.id] = true;
}
loopThroughChildren(obj._children);
return idsHashMap;
}
// Sets checked in data to false if an id exists in object
function setCheckedValue(obj) {
const idsHash = getIdsHashMap(object);
const loopThgroughChildren = (children) => {
if (!Array.isArray(children)) {
return;
}
children.forEach((child) => {
// Checks, if id exists in hashmap from object
if (idsHash[child.id]) {
child.checked = false;
}
if (child.children) {
loopThgroughChildren(child.children);
}
});
};
if (obj.children) {
loopThgroughChildren(obj.children);
}
return obj;
}
console.log(setCheckedValue(data));

get key values pair from an array of objects and place in new array

I need to keep { label: "Strawberry 🍓", value: "strawberry"}, for this code to work with
the in react though when submitting to the database i would like to have the selected values sent through as strawberry: true, watermelon: true, pear: true,
const options = [
{ label: "Strawberry 🍓", value: "strawberry"},
{ label: "Watermelon 🍉", value: "watermelon" },
{ label: "Pear 🍐", value: "pear" },
]
I would like to convert the above array to an array of
const newArray = [
strawberry: true
watermelon: true
pear: true
]
I would have a clue how you would do it maybe it's a two step thing?
If you really mean an object {strawberry: true, watermelon: true, pear: true} (an associative array), not an Array,
const options = [
{ label: "Strawberry 🍓", value: "strawberry"},
{ label: "Watermelon 🍉", value: "watermelon" },
{ label: "Pear 🍐", value: "pear" },
];
const optionsObject = {};
options.forEach(({value}) => optionsObject[value] = true);
(You can also do this with .reduce if you really want to:)
const optionsObject = options.reduce((obj, {value}) => {
obj[value] = true;
return obj;
}, {});

Angular is not sending objects in objects

I'm sending this JSON with Angular.js to my node.js/express.js service:
{
"name": "MyGuitar",
"type": "electric",
"userid": "123",
"likes": 0,
"dislike": 0,
"guitarParts": {
"body": {
"material": "/content/img/hout.jpg",
"_id": "5566d6af274e63cf4f790858",
"color": "#921d1d"
},
"head": {
},
"neck": {
"material": "/content/img/hout.jpg",
"_id": "556d9beed90b983527c684be",
"color": "#46921d"
},
"frets": {
},
"pickup": {
},
"bridge": {
},
"buttons": {
}
}
}
The guitarParts are not saved in the MongoDB database.
Mongoose inserts the following:
Mongoose: guitars.insert({ name: 'MyGuitar', type: 'electric', userid: '123', likes: 0, _id: ObjectId("557023af9b321b541d4d416e"), guitarParts: [], __v: 0})
This is my Mongoose model:
guitarPart = new Schema({
id: { type: String, required: true },
color: { type: String, required: true },
material: { type: String, required: true },
x: { type: Number, required: false },
y: { type: Number, required: false },
width: { type: Number, required: false },
height: { type: Number, required: false},
});
guitarParts = new Schema({
body: [guitarPart],
neck: [guitarPart],
head: [guitarPart],
bridge: [guitarPart],
frets: [guitarPart],
pickup: [guitarPart],
buttons: [guitarPart]
});
guitar = new Schema({
name: { type: String, required: true, unique: false },
type: { type: String, required: true },
userid: { type: String },
likes: { type: Number },
dislikes: { type: Number },
guitarParts: [guitarParts],
kidsguitar: { type: Boolean },
lefthanded: { type: Boolean },
assemblykit: { type: Boolean }
},
{
collection: 'guitars'
});
I don't know what's going wrong. Any ideas?
According to the mongoose documentation of Subdocuments says: Sub-documents are docs with schemas of their own which are elements of a parents document array
And in your schema you provided: guitarParts is not an array, it is an object and a guitarPart is not array it is an object too. So that's why it is not saving.
So the correct way to model your Schema it would be:
var guitarDefinition = {
_id: {type: String, required: true},
color: {type: String, required: true},
material: {type: String, required: true},
x: Number,
y: Number,
width: Number,
heigth: Number
};
var guitarSchema = Schema({
name: { type: String, required: true, unique: false },
type: { type: String, required: true },
userid: String,
likes: Number,
dislikes: Number ,
kidsguitar: Boolean,
lefthanded: Boolean ,
assemblykit: Boolean,
guitarParts: {
body: guitarDefinition,
neck: guitarDefinition,
head: guitarDefinition,
bridge: guitarDefinition,
frets: guitarDefinition,
pickup: guitarDefinition,
buttons: guitarDefinition
}
});
Actually I have run in my computer and it is saving you can see my complete code here: https://gist.github.com/wilsonbalderrama/f10c38f9fb510865edc2

Resources