How to print the key and value of an object? [duplicate] - javascript

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])
}

Related

How to get index in forEach? [duplicate]

This question already has answers here:
Loop (for each) over an array in JavaScript
(40 answers)
Closed 2 years ago.
I'm inheriting some code from someone else but I never used this way. I used to use
for(var i = 0; i<items.length; ++i; {
items[i];
Or
myArray.forEach(function (value, i) {
items[i];
But what if I use the following?
filtererdData.forEach(regionData => {
index?
Something like this.
filteredData.forEach((regionData, index) => {
// your code here
})
Ref forEach: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Join strings in object name in javascript [duplicate]

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.

How to get sum of array with "for" loop [duplicate]

This question already has answers here:
Loop (for each) over an array in JavaScript
(40 answers)
Closed 6 years ago.
I'm a total newbie in JavaScript. I'm trying to learn it using programming experience in Python...
Let's say there is an array of integers [2,3,4,5]. I want to get sum of all items in it with for loop. In Python this gonna looks like
list_sum = 0
for i in [2,3,4,5]:
list_sum += i
Result is 14
But if I try same in JavaScript:
var listSum = 0;
for (i in [2,3,4,5])
{
listSum += i;
}
This will return 00123. Seems that item indexes concatenated in a string with initial listSum value. How to make code works as intended and to get sum of all array items as integer?
You are doing wrong for loop syntax. check this : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for
var listSum = 0;
var arr = [2,3,4,5];
for (i=0;i<arr.length ; i++)
{
listSum += arr[i];
}
document.write(listSum);

javascript convert array to json object [duplicate]

This question already has answers here:
JavaScript: Converting Array to Object
(2 answers)
Closed 8 years ago.
I've got the following array:
array = [{"id":144,"price":12500000},{"id":145,"price":13500000},
{"id":146,"price":13450000},{"id":147,"price":11500000},
{"id":148,"price":15560000}]
i wanto convert it to json like this:
json = {{"id":144,"price":12500000},{"id":145,"price":13500000},
{"id":146,"price":13450000},{"id":147,"price":11500000},
{"id":148,"price":15560000}}
So than i can store everything in mongodb in a unique document.
Regards,
Just run a loop and equate...like...
var obj = {};
for(var i=0; i<array.length; i++)
{
obj[i] = array[i]
}
It will do
{
0:{"id":144,"price":12500000},
1:{"id":145,"price":13500000},
2:{"id":146,"price":13450000},
3:{"id":147,"price":11500000},
4:{"id":148,"price":15560000}
}
Because your JSON is invalid.
Not sure what you are asking
From array or another variable to json string =>
var str = JSON.stringify(thing);
From a json string to variable
var thing = JSON.parse(str);

Finding values of a mapping/dict [duplicate]

This question already has answers here:
How to get all properties values of a JavaScript Object (without knowing the keys)?
(25 answers)
Closed 9 years ago.
I have map/dictionary in Javascript:
var m = {
dog: "Pluto",
duck: "Donald"
};
I know how to get the keys with Object.keys(m), but how to get the values of the Object?
You just iterate over the keys and retrieve each value:
var values = [];
for (var key in m) {
values.push(m[key]);
}
// values == ["Pluto", "Donald"]
There is no similar function for that but you can use:
var v = Object.keys(m).map(function(key){
return m[key];
});

Categories

Resources