Nothing assign into array element in nodejs app - javascript

I have a problem in my express project that I can't resolve since a day. I can't push some data into array element. Let me demonstrate my code and data.
Here is my result data which coming from mongodb:
result = {
name: 'Workflow',
steps:[
{ name: 'First Step',
assignee: '2cb56eadab3fbdc46dcb896e2ec68f33'
},
{
name: 'Second Step',
assignee: '1h374jab3fbdc46wer896e2ec687as'
}
],
__v: 0
}
Here is my code block:
var save = function(data, next) {
return new Promise(function(resolve) {
if (_.isEmpty(data._id)) {
Workflow.create(data, function (err, result) {
if (err) return next(err);
result.steps.forEach(function(step) {
step.detail = {
fullName: 'blablabla',
avatar: 'blablabla'
}
});
resolve(result);
});
}
}
}
After running code block my expectation is:
result = {
name: 'Workflow',
steps:[
{ name: 'First Step',
assignee: '2cb56eadab3fbdc46dcb896e2ec68f33',
detail: {
fullname: 'blablabla',
avatar: 'blablabla'
}
},
{
name: 'Second Step',
assignee: '1h374jab3fbdc46wer896e2ec687as',
detail: {
fullname: 'blablabla',
avatar: 'blablabla'
}
}
],
__v: 0
}
I can't get my expectation from result data and can't understand why detail is not assign steps array elements?

You can't directly modify the objects that MongoDB gives you, they're frozen.
You can copy the object and assign to the copy:
const copy = {...result, steps: result.steps.map(step => {
const stepCopy = {...step};
stepCopy.detail =
fullName: 'blablabla',
avatar: 'blablabla'
};
return stepCopy;
})};
resolve(copy);
That can actually be written more concisely, but it starts getting hard to read:
const copy = {...result, steps: result.steps.map(step => (
{...step, detail: {
fullName: 'blablabla',
avatar: 'blablabla'
}}
)};
resolve(copy);
Or, since I notice you're using ES5 syntax (but presumably with polyfills):
var copy = Object.assign({}, result);
copy.steps = copy.steps.map(function(step) {
var stepCopy = Object.assing({}, step);
stepCopy.detail = {
fullName: 'blablabla',
avatar: 'blablabla'
};
return stepCopy
)};
resolve(copy);
You'll need a polyfill for Object.assign (or I see Underscore/Lodash in your code, you can use _.extend instead, you literally just replace Object.assign with _.extend in the above).

You can do it in another way. Add detail object in the model itself. Set default value in the model definition.

Related

Retrieving values from array throws error javacript

I am having an array with following values:
[
{
'Admin1': {
id: 'fa1b2731'
},
'Admin2': {
id: '7b5ab064'
},
'Admin3': {
id: '9f462511'
},
'Admin4': {
id: 'aa82421d'
},
'Admin5': {
id: '34cb2b'
},
'Admin6': {
id: 'ff71ffdd'
},
'Admin7': {
id: 'b57ac9e7'
}
}
]
The code i am trying to retrieve each user id from above array is throwing an error->expected undefined not to be undefined
Following is the code snippet:
if (userArray) {
for (const user of Object.values(userArray)) {
const delUserRes = await userApi.deleteUserById({
token: accessToken,
organizationId: orgid;,
userId: user.id
});
the above method reads the userarray corectly but never assign each id to userId form user.id and throws error
The array in example is having one item, what i mean to get user.id you should call array[0].['Admin1'].id. In your code you doing it like array.['Admin1'].id, so thats why it can't find user.id.
try something like this
if (userArray) {
for (const user of Object.values(userArray[0])) {
const delUserRes = await userApi.deleteUserById({
token: accessToken,
organizationId: orgid;,
userId: user.id
});
Your all the user are in single element of array object at 0 index.
try below code
for (const user of Object.values(userArray[0])) {
console.log(user)
}
Basically you are trying to get values from an object inside an array, so the Object.values doesn't make sense in your code. You can simply use userArray[0] in your for loop or map like:
var data = [ { 'Admin1': { id: 'fa1b2731' }, 'Admin2': { id: '7b5ab064' }, 'Admin3': { id: '9f462511' }, 'Admin4': { id: 'aa82421d' }, 'Admin5': { id: '34cb2b' }, 'Admin6': { id: 'ff71ffdd' }, 'Admin7': { id: 'b57ac9e7' } } ]
Object.values(data[0]).map(user => { //your logic here } );

filter function not working in an Array using Node js

I am trying to filter out empty array but its not happening
I was trying to compare value which are present inside my database and fileName
I tried arr.filter(Boolean);
even i tried arr.filter((item)=>item)
PS: fileName is not an array value so I converted it into array.
function checkDoc(data, childProduct, fileName, pathName, req, res) {
return new Promise((resolve, reject) => {
Document.findAll({
raw: true,
where: {
product_id: childProduct.id,
},
})
.then((productDoc) => {
if (productDoc.length === 0) {
return resolve(addDocument(data, childProduct, fileName, pathName));
} else {
let fileArray = [];
fileArray.push(fileName);
productDoc.forEach((singleProduct) => {
let productValue = singleProduct.name;
let unMatchedValues = fileArray.filter((value) =>
productValue.includes(value)
);
let removedBoolean = unMatchedValues.filter((item) => item);
console.log("Document Name: ", removedBoolean);
});
}
})
.catch(function (err) {
return reject("Can't be added please try again :) " + err);
});
});
}
fileName:
ABC
PQR
XYZ
Installation and Configuration
Java
Node Js
where as in singleProduct.name it contain
[ABC]
[PQR]
[Installation and Configuration]
[XYZ]
attached Output Image :
Expected OutPut:
matchedValue:
[`document name: ABC`]
[`document name: PQR`]
[`document name: Installation and configuration`]
[`document name: XYZ`]
unmatchedValue:
['Java']
[`Node Js`]
If you're asking how to filter an array of objects to remove those with empty names, here's an example:
const team = [
{ name: 'max', age: 21 },
{ name: '', age: 19 },
{ name: 'james', age: 33 },
{ name: '', age: 30 },
];
// Log the entire team
console.log('Team:', team);
// Log only those team members with names
console.log('Team with names:', team.filter(x => x.name));
// Log only the names
console.log('Names:', team.filter(x => x.name).map(x => x.name));

I need to unstructure an object to update the variables defined in data

it's my first post. I need to destructure to update a variable defined in "data", I have the following code snippets. I'm using VUE.
data: () => ({
id: '',
phone: '',
email: ''
}),
methods: {
async getId(){
{this.id, this.email, this.phone} = this.$route.query.item
}
}
Actually you can assign to existing variables.
The syntax is just a little weird.
This should work
({id: this.id, phone: this.phone, email: this.email} = this.$route.query.item)
Here's a working example
You can't destructure to existing props but to new ones only:
data () {
return {
item: {
id: '',
phone: '',
email: ''
}
}
},
...
methods: {
async getId(){
{ id, email, phone } = this.$route.query.item
Object.assign(this.item, { id, email, phone })

Set correct value for each property in an object

I have a problem in pushing input into array. I have an array with some properties and I'm going to push some value into it, but I have no idea how to tell which value is for which property.
This is my array that I want to push into it:
validInput: [{
image: avatar1,
name: '',
email: '',
passwrod: '',
phone: '',
revenue: '',
create_date: '',
age: '',
id: ''
}]
This is my function that pushes into the array:
validation(value, REGEX) {
if (REGEX.test(value) === true) {
this.state.validInput.push(value);
this.setState({
validInput: this.state.validInput
});
} else {
console.log('error');
}
}
If I understood correctly and you wish to convert your object inside validInput array into an array of objects you can do this:
Let's say we are looking to get an array of objects with the following format:
{keyName:key,keyValue:value}
we can do something like that:
const newArray = new Array();
Object.keys(this.validInput[0])
.forEach(singleKey => {
newArray.push({
keyName:singleKey,
keyValue:this.validInput[0][singleKey]
})
})
// finally - we will have the newly formatted array in newArray
I think you should have some unique way of identifying the object you want for filtering process like id, name etc. For modified function,
validation(id, value, REGEX) {
if(REGEX.test(value)){
this.state.validInput.map((user) => {
if(user.id === id) {
user.PROPERTY_YOU_NEED_TO_UPDATE = value
}
}
}
}
Since this validInput might receive another object better use to identify it using if(user.id === id). If validInput won't receive another there is no point to use array of objects.
validInput: {
image: avatar1,
name: '',
email: '',
passwrod: '',
phone: '',
revenue: '',
create_date: '',
age: '',
id: ''
}
If it's like above you can just edit the property you want...
this.setState(state => {
let user = Object.assign({}, state.validInput);
user.PROPERTY_YOU_NEED_TO_UPDATE = value;
return { user };
})

Add snapshot.val & snapshot.key to an array while I´m subscribed

I´m gonna break my head with a stone ^^"
I have this code:
this.af.database.list('/Documentos', { preserveSnapshot: true })
.subscribe(snapshots => {
snapshots.forEach(snapshot => {
console.log(snapshot.key, snapshot.val());
});
})
With that I extract all the data correctly, but now I want to add to an object array or something like that (I started few weeks ago with Firebase + Angular2).
I wanna fill that array to load the [ng2 smart table] and if I´m thinking partially well with a properly well-formed array I will fill the table but I don´t know how. Hope anyone can help.
If you want an map (object) with key: value, you can easily do this with Array.prototype.reduce():
const map = snapshots.reduce((map, snapshot) => {
map[snapshot.key] = snapshot.val();
}, {});
Well, according to the example : https://akveo.github.io/ng2-smart-table/#/examples/using-filters ...
(You can find the source code here: https://github.com/akveo/ng2-smart-table/blob/master/src/app/pages/examples/filter/basic-example-source.component.ts)
... you have to put your data in a JSON object :
settings = {
columns: {
id: {
title: 'ID',
filter: false,
},
name: {
title: 'Full Name',
filter: false,
},
username: {
title: 'User Name',
filter: false,
},
email: {
title: 'Email',
filter: false,
}
}
};
data = [
{
id: 1,
name: 'Leanne Graham',
username: 'Bret',
email: 'Sincere#april.biz',
},
{
id: 2,
name: 'Ervin Howell',
username: 'Antonette',
email: 'Shanna#melissa.tv',
}
];
"settings" contain your columns names and "data" must match the columns from "settings".
It would be easier if we knew a bit more of your code (columns of your table + data returned by your service), but I assume something like that would work :
data = [];
this.af.database.list('/Documentos', { preserveSnapshot: true })
.subscribe(snapshots => {
snapshots.forEach(snapshot => {
data.push(
{ [snapshot.key]: snapshot.val() }
);
});
})
Please note that this will create a JSON array with only one key/val per row. We do need to know more about your data to give you a propre answer.
Ok, I found the solution with a simple Array() x)
this.af.database.list('/Documentos', { preserveSnapshot: true })
.subscribe(snapshots => {
snapshots.forEach(snapshot => {
let length = todo.documentos.push(snapshot.val()); // documentos is an array in the class
todo.source.load(todo.documentos);
});
});

Categories