I have been trying this fora a little while and cannot get it.
I have a piece of code to create an Array of an objects which is something like this :
var allUsers = new Array();
function addObjectToArray(userData){
colorCode = '#'+Math.floor(Math.random()*16777215).toString(16);
userImage = "avatar"+Math.floor(Math.random()*11)+".jpg";
newuserData = {};
newuserData[userData.userID] = {"nickName":userData.nickName,"SocketId":socket.id,"colorCode":colorCode,"userImage":userImage};
allUsers.push(newuserData);
}
So this function adds a new Object to array everytime it is called and after calling this function twice with different params i get an array something like this
[ { '886':
{ nickName: 'MOhan',
SocketId: '9AMRe2v2e-hWuMeBAAAC',
colorCode: '#d3af07',
userImage: 'avatar6.jpg' } },
{ '172':
{ nickName: 'Anil',
SocketId: 'a5VU5pCzWecMHM2FAAAD',
colorCode: '#22b913',
userImage: 'avatar4.jpg' } } ]
What i want instead is an object something like this :
{
'886':
{ nickName: 'MOhan',
SocketId: '9AMRe2v2e-hWuMeBAAAC',
colorCode: '#d3af07',
userImage: 'avatar6.jpg' } ,
'172':
{ nickName: 'Anil',
SocketId: 'a5VU5pCzWecMHM2FAAAD',
colorCode: '#22b913',
userImage: 'avatar4.jpg' }
}
What changes should i make to the code.
Easy, objects aren't technically pushed to but instead you define new keys on that object.
Switch your Array for an object literal and just add the key to it.
var allUsers = {};
function addObjectToObject(userData) {
//logic
allUsers[userData.userId] = newuserData;
}
Related
DATA STORE FILE:
let data = {
users: [],
channels: [],
};
// Use get() to access the data
function getData() {
return data;
}
// Use set(newData) to pass in the entire data object, with modifications made
function setData(newData) {
data = newData;
}
export { getData, setData };
clearV1() FILE:
import { getData, setData } from './dataStore';
function clearV1() {
let data = {
users: [],
channels: [],
};
setData(data);
return {};
}
export { clearV1 };
When running the clearV1() function in another, it does not clear the data store. For example:
authRegisterV1 creates a user and adds them to the data store
channelCreateV1 creates a channel and adds it to the data store
authRegisterV1('test1#gmail.com','test123','Firt','Last');
clearV1()
authRegisterV1('test2#gmail.com','test123','Firt','Last');
expected output:
{
users: [
{
uId: 1,
email: 'test2#gmail.com',
password: 'test123',
nameFirst: 'Firt',
nameLast: 'Last',
handle: 'firtlast0',
permissionId: 2
}
],
channels: [],
}
wrong output:
{
users: [
{
uId: 1,
email: 'test1#gmail.com',
password: 'test123',
nameFirst: 'Firt',
nameLast: 'Last',
handle: 'firtlast',
permissionId: 1
},
{
uId: 2,
email: 'test2#gmail.com',
password: 'test123',
nameFirst: 'Firt',
nameLast: 'Last',
handle: 'firtlast0',
permissionId: 2
}
],
channels: [],
}
I believe the implementation of the clearV1() function is correct, what other possible reason could there be for this error? I imported all the used functions into the test file.
I think the problem your facing is the fact that you created data inside of ./dataStore, and thus, it does not exist in clearV1() file. Another way to put is, when you made the data variable initially, it was made in ./dataStore and only exists there. So it makes a new variable instead of updating the existing one.
Another problem is, you are trying to using let data = [value]. let creates the variable just inside of the function you called it in, ignoring any variables on the outside. As a rule of thumb in javascript, when updating an existing variable, use [name] = [value].
If you want to learn more, here's the MDN docs for import statements and let statements.
I have this code that set the obj value in localstorage.
const obj = {
name: "Bill",
meta: {
age: 18
}
};
const data = localStorage.setItem('user', JSON.stringify(obj));
Now i want to change the age key in the localstorage:
localStorage.setItem('user', JSON.stringify({ ...data, ...data.meta.age= 15 } }));, but it does not work.
How to change the value above and to see the changes in localstorage?
Assuming you have data, the problem is that ...data.meta.age = 15 is a syntax error. You don't use = in object literals, and it does't make sense to try to spread the age property (which is a number). Instead:
const newData = {
...data,
meta: {
...data.meta,
age: 15,
},
};
localStorage.setItem("user", JSON.stringify(newData));
Notice how we have to create a new outermost object and also a new object for meta.
Live Example:
const data = {
name: "Bill",
meta: {
occupation: "Programmer", // Added so we see it get copied
age: 18,
},
};
const newData = {
...data,
meta: {
...data.meta,
age: 15,
},
};
console.log(newData);
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 };
})
I have a function to which I am passing the state of an object. Inside the function I am performing some operations on the state. Now I want to update the state with the operations I have performed and display it as an JSON object.
I have my state as :
state= {
company: "xyz",
employee: {
name:["a","b"],
age: [13,14]
},
details: {
salary:[],
dept:[]
}
}
}
I have a function in which I have populated the values of salary and dept
function updatestate(state){
//some operations..
//const output has values
//output variable has something like this stored in it=>
// salary:[["2500"],["4000"]] , dept:[["fin"],["mkt"]]
}
the state object passed has all the values; now I want to append the values of salary and dept inside filters.
Expected output is :
state= {
company: "xyz",
employee: {
name:["a","b"],
age: [13,14]
},
details: {
salary:[["2500"],["4000"]] ,
dept:[["fin"],["mkt"]]
}
}
}
I tried manual coding:
//inside the function updatestate(state)
const state_json = {details : output}
return JSON.stringify(state_json);
But I want to show the entire state and find a way to automatically append the values into the state and display as JSON
I'm not sure with your issue, but I think you can use JSON.stringify() Fn for the same.
let state= {
company: "xyz",
employee: {
name:["a","b"],
age: [13,14]
},
details: {
salary:[],
dept:[]
}
};
function updatestate(state) {
const baseData = {
salary:[["2500"],["4000"]] ,
dept:[["fin"],["mkt"]]
};
state.details.salary = baseData.salary;
state.details.dept = baseData.dept;
return state;
}
state = updatestate(state);
console.log(JSON.stringify(state));
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.