This question already has answers here:
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 5 years ago.
I need to join two strings in the name of the object in for loop in mongoose and expressjs like in example:
for(var i = 0; i < 2; i++)
{
EnrollSessions.update({ CookieId: req.cookies.UserEnrollSession },
{$set: {"Files.File"+i+".RealName": file.originalname},
function (err,data) {
console.log(data);
});
}
As a result i need update value of Files.File1.Realname, Files.File2.Realname.
Is it possible?
Thank you for help in advance.
In your example the for loop runs with i values 0 and 1 which would rename File0 and File1.
You can use "Files.File"+ (i + 1) +".RealName".
A better approach would be to create the update object in the for loop and the send it to mongo afterwards.
let obj = {
};
for(var i = 0; i < 2; i++)
{
let name = "Files.File" + (i + 1) + ".RealName";
obj[name] = file.originalname;
}
EnrollSessions.update({ CookieId: req.cookies.UserEnrollSession },
{$set: obj},
function (err,data) {
console.log(data);
});
Or, if there are only 2 files you can hard code them by hand in the same update object instead of the for loop.
Related
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 2 years ago.
I'm trying to find out how to initialise an array of objects, where each object has the index (i) as its key and 0 as its value. The code below is not working as expected but I can't see why. I'm still quite beginner with Javascript and couldn't find an answer elsewhere.
var n = 10;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({i : 0});
you should use this syntax sample.push({[i]: 0});
when you need to access object property which is stored under some variable you should always use square brackets no matter you need write to or read from an object
The code below should take care of the job:
let n = 10;
let sample = Array.from({length:n}, (_, i) => ({ [i]: 0 }));
As pointed by Oleksandr Sakun on his answer, the index is used between brackets in order to evaluate the variable and set as a property of the object.
For a funcitonal approach you can try:
const initArray = (n)=>{
const newArr = new Array(n).fill(0);
return newArr.map((value, index)=> ({[index]: value}))
}
add square brackets to the index [i] :
var n = 10;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({[i]: 0});
console.log(sample);
This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 5 years ago.
I have an object like this
var data = {'name':'test','rollnum':'3','class':'10'};
I want to console it by iterating through it like,
name:test
rollnum:3
class:10
Can anyone please help me.Thanks.
This will work for values that are Strings or Numbers.
var data = {'name':'test','rollnum':'3','class':'10'};
var i;
for (i in data) {
console.log(i + ":" + data[i]);
}
With modern JavaScript syntax, this becomes quite elegant:
const data = {'name':'test','rollnum':'3','class':'10'};
Object.entries(data).forEach(([key, val]) => console.log(`${key}: ${val}`));
for(i in data) {
console.log (i,':', data[i])
}
This question already has answers here:
How to keep an Javascript object/array ordered while also maintaining key lookups?
(2 answers)
Closed 7 years ago.
I have got a function which retrieves an object.
This object has a property and a value. The property is numeric and starts at "-30" all the way up to "50"
The problem is that when I loop through this object the browser seems to order it starting at "0" instead of starting at the initial property of "-30"
I need to make sure the order is exactly the same as the object.
var colorOj = {
"-30":"#111","-29":"#131313", ..etc.., "0":"#333", ..etc..,
"50":"#555"
}
function makeList(object){
for (var i in object) {
console.log(i); // Returns 0,1,2,3,4,5
// I need a return of -30,-29,-28,..., 0, 1, 2 ...
}
}
makeList(colorObj);
As suggested by #Teemu, properties are not stored in any specific order. But you can print them in any order using specific sort function accordingly.
Code
var obj = {};
for (var i = 5; i > -5; i--) {
obj[i * 10] = i * 10;
}
// Sort and get all keys...
var keys = Object.keys(obj).sort(function(a, b) {
return parseInt(a) - parseInt(b);
});
console.log(keys)
// Loop over keys to print values of each property
keys.forEach(function(item) {
console.log(item, obj[item]);
})
You can do something like this maybe:
var colorOj = {
"-30":"#111","-29":"#131313", "0":"#333",
"50":"#555"
};
var keys = Object.keys(colorOj).sort(function(a,b){return a - b})
for(var i = 0; i < keys.length;i++){console.log(keys[i])}
This way you can get every key in the object. Then sort it however you like(the sort function in javascript can take a compare function as a parameter look -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
This question already has answers here:
Create an array with same element repeated multiple times
(25 answers)
Closed 7 years ago.
I'm wondering if there is a way to create javascript/jquery array in one-liner to receive something like:
my_array = ['-', '-', ,'-' ,'-']
Idea is that array should be created with dynamic length and all values filled with given value.
Thanks in advance!
Try:
var total = 4;
var my_array = new Array(total + 1).join("-").split("");
document.write(JSON.stringify(my_array))
.fill Support The native function will be added in (ECMAScript 6), but for now is not available.
if(!Array.prototype.fill){
Array.prototype.fill = function(val){
for (var i = 0; i < this.length; i++){
this[i] = val
}
return this
}
}
var my_array = new Array(4).fill("-"); //returns ["-","-","-","-"]
Try to use:
Array.apply(null, new Array(63)).map(String.prototype.valueOf,"-")
This question already has answers here:
How do I remove an object from an array with JavaScript? [duplicate]
(15 answers)
Closed 9 years ago.
How can I remove an object from an Array by id for example:
users = [{id: "10051", name: "Mike Coder"},{id: "4567", name: "Jhon Second"}]
Say I want to remove user with id "10051" using javascript, I tried searching the internet but couldn't find anything?
plus I do not want to use underscore!
plus I do not want to use underscore!
The native method for this is .filter():
var removeId = "4567";
users = users.filter(function (user) { return user.id !== removeId; });
Note that it requires the engine be ES5-compatible (or a polyfill).
You could use .filter method of array.
users = users.filter(function(el) {return el.id !== '10051'});
for (var i = 0; i < users.length; ++i)
{
if ( users[i].id == "10051" )
{
users[i].splice(i--, 1);
}
}
var users= [{id:"10051", name:"Mike Coder"},{id:"4567", name:"Jhon Second"}];
/* users.length= 2 */
function removebyProperty(prop, val, multiple){
for(var i= 0, L= this.length;i<L;i++){
if(i in this && this[i][prop]=== val){
this.splice(i, 1);
if(!multiple) i= L;
}
}
return this.length;
}
removebyProperty.call(users,'id',"10051");
returned value: (Number) 1