map method not working at some place using javascript / node js - javascript

I have Output in JSON format and i want to specific field from it
{
"id":"01",
"name":"fish",
"Data.id":"f01",
"Data.path":"/home/work/fish.jpg"
}
I am using map function to get the value but the problem is i can only fetch the value of id and name not Data.id and Data.path
so i am getting this value from my database and this is my code by how i am getting the value from database
function runRest(req, res) {
let data = req.body;
Owner.findAll({
raw: true,
where: {
id: data.id,
},
include: {
model: kingdom,
required: false,
},
attributes: ["id", "name"],
})
.then((parents) => {
parents.map((value) => {
console.log(value);
});
})
.catch(function (err) {
console.log(err);
});
}
let value={
"id":"01",
"name":"fish",
"Data.id":"f01",
"Data.path":"/home/work/fish.jpg"
};
value.map((data)=>{
console.log(data.id);
});
I can only fetch data which is in white font color which is ID and name any solution how can i get Data.id and Data.path by using map function
I even tried this
let links = value
.map((child) => {
for (let i in child)
if (i === "Data.id") {
return child[i];
}
})
but i don't want to use this for method any chance I can use Map function ?

The object
values = {
"id":"01",
"name":"fish",
"Data.id":"f01",
"Data.path":"/home/work/fish.jpg"
};
Has the keys: "id", "name", "Data.id", "Data.path"
To get the value "f01" you must use the key "Data.id":
foo = values["Data.id"]; // foo === "f01"
In the comments you mention that you want to map an array of these objects to the data id:
idArray = objects.map(value => value["Data.id"]);

Related

How to copy the elements of an array into an array in a Mongodb document

I have an array
let data = [a, b, c, d, e];
And I want to insert the elements of this array into an array in a MongoDb document. This is my schema.
const userSchema = mongoose.Schema({
info: reqString,
data: [String]
});
As you can see the data field represents an array. In my index.js I use a for-loop to iterate through the array.
for(var i= 0; i < data.length; i++){
connectToDb(data[i]);
}
And the connectToDb() is here:
const connectToMongoDB = async (_data) => {
await mongo().then(async (mongoose) => {
try {
console.log('Connected to mongodb!');
await userSchema.findOneAndUpdate({
info: 'facts',
}, {
$push: {
data: _data,
}
});
} finally {
mongoose.connection.close();
console.log('Disconnected from mongodb!');
}
});
}
However although a documents is created in MongoDb, the data field which represents the array remains empty. I welcome all suggestions
From your question it is not clear if you want to set the data field value with your _data array, or append your _data array to the existing array in the data field.
1. To replace the array of the data field:
await userSchema.findOneAndUpdate(
{ info: 'facts' },
{ $set: { data: _data } }
).exec();
2. To append an array to the array of the data field:
await userSchema.findOneAndUpdate(
{ info: 'facts' },
{ $push: { data: { $each: _data } } }
).exec();

Change Nested State Value With A Single Function? (javascript/React)

I have some react user privilege state data I need to manage. I would like the ability to change the object privileges based on their property through a dynamic function. I'm not sure how to target the specific nested privilege property to change the value. Is this possible?
Question: How can I change the value of a nested privilege property to the functions type and value parameter?
Heres an Example:
const [userPrivilages, setUserPrivilages] = useState([{
_id: "123"
privilages: {
edit: true, //before!
share: true,
del: false
}
},
{
...more users
}
])
//my attempt
const changePrivilage = (type, value) => {
const newPrivilages = userPrivilages.map(user => {
return {
...user,
privilages: {
...privilages,
//change the privilage of "type" from the functions parameter to the value parameter
}
}) setUserPrivilages(newPrivilages)
}
changePrivilage("edit", false)
Desired output:
const [userPrivilages, setUserPrivilages] = useState([{
_id: "123"
privilages: {
edit: false, //After!
share: true,
del: false
}
},
{
...more users
}
])
Thanks!
You can use [] to refer to variable as a key like below:
const changePrivilage = (type, value) => {
const newPrivilages = userPrivilages.map(user => {
return {
...user,
privilages: {
...user.privilages,
[type]: value // here it is !!!
}
}) setUserPrivilages(newPrivilages)
}
Try this :
(see comments for understanding code)
const changePrivilage = (type,value) => {
const newUserPrivilages = userPrivilages.map(user => {
let newPrivilages = user.privilages; // get old privilages of user
newPrivilages[type] = value; // update type with new value
return {
...user,
privilages: newPrivilages, // set privilages as newPrivilages
};
});
setUserPrivilages(newUserPrivilages);
};
Note : this will change properties for all users. If you want to update only for specific user, pass _id as well to changePrivilage and execute newPrivilages[type] = value; // update type with new value inside if condition comparing user _id.

Edit function not saving changes to state data in React

I am trying to provide functionality in my webpage for editing state data.
Here is the state structure
state = {
eventList:[
{
name: "Coachella"
list: [
{
id: 1,
name: "Eminem"
type: "rap"
}
{
id: 2,
name: "Kendrick Lamar"
type: "rap"
}
]
}
]
}
I want to be able to edit the list arrays specifically the id, name, and type properties but my function doesn't seem to edit them? I currently pass data I want to override id name and type with in variable eventData and an id value specifying which row is selected in the table which outputs the state data.
Here is the function code:
editPickEvent = (eventData, id) => {
const eventListNew = this.state.eventList;
eventListNew.map((event) => {
event.list.map((single) => {
if (single.id == id) {
single = eventData;
}
});
});
this.setState({
eventList: eventListNew,
});
};
When I run the code the function doesn't alter the single map variable and I can't seem to pinpoint the reason why. Any help would be great
edit:
Implementing Captain Mhmdrz_A's solution
editPickEvent = (eventData, id) => {
const eventListNew = this.state.eventList.map((event) => {
event.list.map((single) => {
if (single.id == id) {
single = eventData;
}
});
});
this.setState({
eventList: eventListNew,
});
};
I get a new error saying Cannot read property list of undefined in another file that uses the map function to render the state data to the table?
This is the part of the other file causing the error:
render() {
const EventsList = this.props.eventList.map((event) => {
return event.list.map((single) => {
return (
map() return a new array every time, but you are not assigning it to anything;
editPickEvent = (eventData, id) => {
const eventListNew = this.state.eventList.map((event) => {
event.list.forEach((single) => {
if (single.id == id) {
single = eventData;
}
});
return event
});
this.setState({
eventList: eventListNew,
});
};
const editPickEvent = (eventData, id) => {
const updatedEventList = this.state.eventList.map(event => {
const updatedList = event.list.map(single => {
if (single.id === id) {
return eventData;
}
return single;
});
return {...event, list: updatedList};
});
this.setState({
eventList: updatedEventList,
});
}
Example Link: https://codesandbox.io/s/crazy-lake-2q6ez
Note: You may need to add more checks in between for handling cases when values could be null or undefined.
Also, it would be good if you can add something similar to the original data source or an example link.
Turns out primitive values are pass by value in javascript, which I didn't know and why the assignment wasn't working in some of the previous suggested answers. Here is the code that got it working for me:
editEvent = (EventData, id) => {
const eventListNew = this.state.eventList.map((event) => {
const newList = event.list.map((single) => {
return single.id == id ? EventData : single;
});
return { ...event, list: newList };
});
this.setState({
eventList: eventListNew,
});
};

Is their any better way to set duplicate array data instead of use data[0]

What is the best way to refactoring code and best performance Here Is what I do In getData function I query get Data from databae using async/await then I got some ugly data I try to map and delete element that duplicate data
async getData({req,res}) {
let data = await this.getData()
data = [
{
"id": 3,
"employee_id": 2290,
"getId": {
"id": 9070
},
"getName": {
"name": "test"
},
},
{
"id": 4,
"employee_id": 2291,
"getId": {
"id": 9070
},
"getName": {
"name": "test"
},
}
] //example I await call database get data look like this
//before I remove them I want to keep duplicate data I set new variable for keep them
//which part is the most ugly is their anyway to do something about this ?
const getId = data[0].getId
const getName = data[0].getName
// in this part I map and delete element that duplicate which is data.getName and data.getId
// I create seperate function for code clean
data = await this.removeElement(data)
//after that I return response data
return response.status(200).json({
status: 200,
success: true,
getId: getId,
getName: getName,
data: data
});
}
async removeElement(data) {
// im not sure is their any beeter way to do something like this ?
return Promise.all(
data.map(async item => {
await delete item.getId;
await delete item.getName;
return item;
})
);
}
so my output response will look like this :
getId : {
id : 9070
}
getName : {
name : 'test'
}
data : [
{
"id": 3,
"employee_id": 2290,
},
{
"id": 4,
"employee_id": 2291,
}
]
I really appreciate for your help thanks
Removing properties from an object is not an asynchronous process. There's no need to await it or have a Promise.all around such a loop.
To extract the two common properties from the first item of the array concisely, you can destructure:
const { getId, getName } = data[0];
Shorthand property names will help too. In full:
const data = await this.getData();
const { getId, getName } = data[0];
const trimmedData = data.map(({ id, employee_id }) => ({ id, employee_id }));
return response.status(200).json({
status: 200,
success: true,
getId,
getName,
data: trimmedData
});
The data.map(({ id, employee_id }) => ({ id, employee_id })) takes the array and constructs a new array of objects which contain only the id and employee_id properties in the original objects.
If you need to blacklist properties rather than extract the desired properties, then you can do something similar to the above with rest syntax:
const trimmedData = data.map(({ getId, getName, ...rest }) => rest);

Firebase retrieve Object by Key in JavaScript Api

Help:
I'm an object of Firebase and can not recover only one item from the list because the key is a objectId and the doc api JS Firebase, it does not have a method to recover for me.
Can you help me?
Controller
var rooms = Rooms.all();
console.log('All Rooms:', rooms);
console.log('Rooms length:', rooms.length);
// New test room
if (!rooms) {
var objRooms = [
{
cc: 'Business 1',
name: 'Chat 1',
city: 'Curitiba',
state: 'PR'
},
{
cc: 'Business 2',
name: 'Chat 2',
city: 'Floripa',
state: 'SC'
}
]
var objRoom = Rooms.save(objRooms);
console.log('ROOMID: ', objRoom.key());
}
Service
.factory('Rooms', function ($firebaseObject) {
// Might use a resource here that returns a JSON array
var ref = new Firebase(firebaseUrl);
var rooms = $firebaseObject(ref.child('rooms'));
return {
all: function () {
return rooms;
},
get: function (roomId) {
// Simple index lookup
console.log('ROOMD:', rooms);
return rooms[ ref.child(roomId) ];
},
save: function (roomData) {
var obj = ref.child('rooms');
var onComplete = function (error) {
if (error) {
console.log('Data could not be saved: ', error);
}
else {
console.log('Data saved successfully!');
}
};
return obj.push(roomData, onComplete);
}
}
})
Output:
Chat Controller initialized!
controllers.js:117 Object {params: Object, current: Object, $current: extend, transition: null}$current: extendcurrent: Objectget: (stateOrName, context)go: go(to, params, options)href: href(stateOrName, params, options)includes: includes(stateOrName, params, options)is: is(stateOrName, params, options)params: ObjectroomId: "-JxlCvzgbdkQfoA1Of78"__proto__: Objectreload: reload()transition: nulltransitionTo: transitionTo(to, toParams, options)__proto__: Object
services.js:78 Selecting the room with id: -JxlCvzgbdkQfoA1Of78
services.js:20 ROOMD: d {$$conf: Object, $id: "rooms", $priority: null}
app.js:43 Logged in as : simplelogin:2
The factory Rooms is a problem:
get: function (roomId) {
// Simple index lookup
console.log('ROOMS:', rooms);
console.log('ROOM specified:', ref.child(roomId).key());
return rooms[ ref.child(roomId) ];
},
[Update]
I created the factory Objects for filter Object data:
.factory('Objects', function () {
return {
filter: function (objectValues, objectKey) {
// to take an action after the data loads, use the $loaded() promise
objectValues.$loaded().then(function () {
// To iterate the key/value pairs of the object, use angular.forEach()
angular.forEach(objectValues, function (value, key) {
if (key === objectKey) {
console.log(objectValues[objectKey]);
return objectValues[objectKey];
}
});
});
}
}
})
and Rooms factory, I edited method get and set:
get: function (roomId) {
return Objects.filter(rooms, roomId);
},
[Update]
I have a database based in the image:
I need list object data.
JavaScript Api
https://www.firebase.com/docs/web/api/
First of all you should use Angularfire which provides some useful methods for using Firebase with AngularJS. You can find the documentation here:
https://www.firebase.com/docs/web/libraries/angular/api.html
Now, your question is how to access an single item using it's key. You can do that simply by just providing the url to that object when retrieving either a $firebaseArray or $firebaseObject (when using Angularfire API):
http://myfirebase.firebase.io/blazing-heat-9118/rooms/ + roomId
And then pass this url to a new Firebase() call:
var ref = new Firebase('http://myfirebase.firebase.io/blazing-heat-9118/rooms/' + roomId);
var room = $firebaseObject(ref);
// To take an action after the data has finished loading, use the $loaded() promise
obj.$loaded().then(function(res) {
console.log(res); // res will be the room object
// To iterate the key/value pairs of the object, use angular.forEach()
angular.forEach(obj, function(value, key) {
console.log(key, value);
});
});
Now you will have fetched the single room from the database.
I'd suggest reading through the Angularfire documentation thoroughly as it contains some great methods for handling your data.

Categories

Resources