I have a application where I need count my doors. For example:
door1 has 60 people
door2 has 70 people
But how can I get the sum of each door because. I want push the sum of each door to my db, this data I get from my client every minute then I push the results to my db, and I clear the array for a next set of objects.
var a = [
{door: 1 , people: 20},
{door: 2 , people: 20},
{door: 1 , people: 10},
{door: 1 , people: 20},
{door: 2 , people: 50},
]
This a great example of when you can use map() and reduce() together:
Array.prototype.map() will run a function on each item in an array and transform each item into something else (returning a new array of the same length).
Array.prototype.reduce() will cumulatively calculate a single value based on each value in an array (returning just a single value).
var total = a.map(function(e) {
return e.people
})
.reduce(function(a, b) {
return {a + b};
})
In the example above we first use map() to transform each object in the array into just its 'people' value. So after this step we have an array that looks like:
[20, 20, 10, 20, 50]
Then we call reduce() on that array, which cumulatively adds the numbers together.
In ES6, this can be written even more succintly as:
let total = a.map(o => o.people).reduce((a,b) => a + b);
var a = [
{door: 1 , people: 20},
{door: 2 , people: 20},
{door: 1 , people: 10},
{door: 1 , people: 20},
{door: 2 , people: 50},
];
var sum = {};
for(var i=0;i<a.length;i++){
sum[a[i].door] = sum[a[i].door] || 0;
sum[a[i].door] += a[i].people;
}
console.log(sum);
var result = {}
a.map(i => result[i.door] = (result[i.door] || 0) + i.people)
and now just console.log(result)
Or you can even enhance the code using some syntactic sugar like that:
var result = {}
a.map({door, people} => result[i.door] = (result[door] || 0) + people)
values=[1,2].map(door=>a.filter(d=>d.door==door).reduce((val,d)=>val+d.people,0));
values will be [60,70],
For every door (1 and 2), get all elems of a where the elems door is door, then join these elems people value and map it back to the array. So every door is replaced with its referring value.
If you dont know the doors, you could create an associative object:
values=a.reduce((all,elem)=>{ return all[elem[door]]=all[elem.door]||0,all[elem.door]+=elem.people;},{});
this will result in:
{
1:60,
2:70
}
var array = [
{door: 1 , people: 20},
{door: 2 , people: 20},
{door: 1 , people: 10},
{door: 1 , people: 20},
{door: 2 , people: 50},
]
var res = [];
array.forEach(function(element) {
var e = res.find(function(data) {
return data.door == element.door;
});
if(e) {
element.people = e.people + element.people;
} else {
res.push({
door: element.door,
people: element.people
});
}
});
I don't know your desired result format, but if an object is good and taking into account you don't know about your doors beforehand, using just reduce() could be enough.
var a = [
{door: 1 , people: 20},
{door: 2 , people: 20},
{door: 1 , people: 10},
{door: 1 , people: 20},
{door: 2 , people: 50},
]
var result = a.reduce((accumulator, currentValue) => {
if (!accumulator[currentValue.door]) {
// set property the first time you find a door
accumulator[currentValue.door] = 0;
}
// sum the number of people each door in each iteration
accumulator[currentValue.door] += currentValue.people;
return accumulator;
}, {});
console.log(result)
The code above is easier to understand, but is a bit verbose. The callback of reduce() can be abbreviated like this:
a.reduce((accumulator, currentValue) => {
accumulator[currentValue.door] = accumulator[currentValue.door] || 0;
accumulator[currentValue.door] += currentValue.people;
return accumulator;
}, {});
Related
I'm making a simple RPG and trying to calculate which attribute should be increased when a character levels up. They have a potential limit for each attribute and I want to increment the attribute that is furthest from its potential.
I can loop through each attribute and subtract its current value from its potential value to get the difference. I can then push the difference to an array. The result looks like:
[
{Strength: 5},
{Dexterity: 6},
{Constitution: 3},
{Wisdom: 4},
{Charisma: 8}
]
Charisma is the key with the highest difference, so how can I evaluate this and return the name of the key (not the value itself)?
EDIT: Here is the logic which is used to get the array:
let difference = [];
let key;
for (key in currentAttributes) {
difference.push({[key]: potentialAttributes[key] - currentAttributes[key]});
};
Simple reduce with Object.entries
const items = [
{ Strength: 5 },
{ Dexterity: 6 },
{ Constitution: 3 },
{ Wisdom: 4 },
{ Charisma: 8 }
]
const biggest = items.reduce((biggest, current, ind) => {
const parts = Object.entries(current)[0] //RETURNS [KEY, VALUE]
return (!ind || parts[1] > biggest[1]) ? parts : biggest // IF FIRST OR BIGGER
}, null)
console.log(biggest[0]) // 0 = KEY, 1 = BIGGEST VALUE
Your data model is a bit weird with the array with objects, a better model would just be an object.
const items = {
Strength: 5,
Dexterity: 6,
Constitution: 3,
Wisdom: 4,
Charisma: 8
}
const biggest = Object.entries(items)
.reduce((biggest, current, ind) => {
const parts = current
return (!ind || parts[1] > biggest[1]) ? parts : biggest
}, null)
console.log(biggest[0])
You could create an object, take the entries and reduce the entries by taking the entry with the greatest value. At the end take the key from the entry.
var data = [{ Strength: 5 }, { Dexterity: 6 }, { Constitution: 3 }, { Wisdom: 4 }, { Charisma: 8 }],
greatest = Object
.entries(Object.assign({}, ...data))
.reduce((a, b) => a[1] > b[1] ? a : b)
[0];
console.log(greatest);
Sort in descending order and grab the first item:
let attributes = [
{Strength: 5},
{Dexterity: 6},
{Constitution: 3},
{Wisdom: 4},
{Charisma: 8}
];
//for convenience
const getValue = obj => Object.values(obj)[0];
//sort descending
attributes.sort((a, b) => getValue(b) - getValue(a));
let highest = attributes[0];
console.log(Object.keys(highest)[0]);
Alternatively, go though the array and find the highest score:
let attributes = [
{Strength: 5},
{Dexterity: 6},
{Constitution: 3},
{Wisdom: 4},
{Charisma: 8}
];
//for convenience
const getValue = obj => Object.values(obj)[0];
//find the highest score
let highest = attributes.reduce((currentHighest, nextItem) => getValue(currentHighest) > getValue(nextItem) ? currentHighest : nextItem);
console.log(Object.keys(highest)[0]);
I'm getting info from an api, and what i wanna do is to multiply two different values from that response, and then sum the totals. I know how to sum all the values with reduce:
function getHistoricSales(){
$http.get('api/SomeApi')
.then(function(data){
$scope.salesResult = data.data.Response;
var hResults = $scope.salesResult.reduce((a, b) => a + b.Cost, 0);
$scope.historic = hResult.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
});
}
But, if per example, on that response not only get the Cost (b.Cost), but the Quantity too. So, how can i in first place multiply every Costby it's own Quantity and then sum the results?
I'm using Javascript and AngularJs.
Hope you can help me. Thanx in advance...
I think what you're looking for is:
var hResults = $scope.salesResult
.map(sr => sr.Cost * sr.Quantity)
.reduce((a, b) => a + b);
So you want to transform each sales result (with map) into its own result (i.e. cost * quantity) and then sum those (with reduce).
For example:
let data = [
{Cost: 10, Quantity: 15},
{Cost: 5, Quantity: 11},
{Cost: 2, Quantity: 110},
{Cost: 5, Quantity: 90},
]
let result = data
.map(sr => sr.Cost * sr.Quantity)
.reduce((a, b) => a + b);
console.log(result);
If each item in $scope.salesResult optionally has a quantity property, you'll need to make sure you're not multiplying by an undefined value. Thus, your reduce() should take this condition into account.
var salesResult = [
// Some items only have the cost
{ cost: 10 },
{ cost: 10 },
// Some items might also have a quantity
{ cost: 10, quantity: 10 },
{ cost: 10, quantity: 10 },
];
var hResults = salesResult.reduce((total, result) =>
total + (result.quantity
? result.cost * result.quantity
: result.cost), 0);
console.log(hResults); // 220
I want to cycle through the objects contained in an array and change the properties of each one. If I do this:
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j]);
}
The console should bring up every object in the array, right? But in fact it only displays the first object. if I console log the array outside of the loop, all the objects appear so there's definitely more in there.
Anyway, here's the next problem. How do I access, for example Object1.x in the array, using the loop?
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j.x]);
}
This returns "undefined." Again the console log outside the loop tells me that the objects all have values for "x". How do I access these properties in the loop?
I was recommended elsewhere to use separate arrays for each of the properties, but I want to make sure I've exhausted this avenue first.
Thank you!
Use forEach its a built-in array function. Array.forEach():
yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});
Some use cases of looping through an array in the functional programming way in JavaScript:
1. Just loop through an array
const myArray = [{x:100}, {x:200}, {x:300}];
myArray.forEach((element, index, array) => {
console.log(element.x); // 100, 200, 300
console.log(index); // 0, 1, 2
console.log(array); // same myArray object 3 times
});
Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.
2. Check if any of the elements in an array pass a test
const people = [
{name: 'John', age: 23},
{name: 'Andrew', age: 3},
{name: 'Peter', age: 8},
{name: 'Hanna', age: 14},
{name: 'Adam', age: 37}];
const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true
3. Transform to a new array
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]
Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.
4. Sum up a particular property, and calculate its average
const myArray = [{x:100}, {x:200}, {x:300}];
const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300
const average = sum / myArray.length;
console.log(average); // 200
5. Create a new array based on the original but without modifying it
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => {
return {
...element,
x: element.x * 2
};
});
console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]
6. Count the number of each category
const people = [
{name: 'John', group: 'A'},
{name: 'Andrew', group: 'C'},
{name: 'Peter', group: 'A'},
{name: 'James', group: 'B'},
{name: 'Hanna', group: 'A'},
{name: 'Adam', group: 'B'}];
const groupInfo = people.reduce((groups, person) => {
const {A = 0, B = 0, C = 0} = groups;
if (person.group === 'A') {
return {...groups, A: A + 1};
} else if (person.group === 'B') {
return {...groups, B: B + 1};
} else {
return {...groups, C: C + 1};
}
}, {});
console.log(groupInfo); // {A: 3, C: 1, B: 2}
7. Retrieve a subset of an array based on particular criteria
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}]
Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
8. Sort an array
const people = [
{ name: "John", age: 21 },
{ name: "Peter", age: 31 },
{ name: "Andrew", age: 29 },
{ name: "Thomas", age: 25 }
];
let sortByAge = people.sort(function (p1, p2) {
return p1.age - p2.age;
});
console.log(sortByAge);
9. Find an element in an array
const people = [ {name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67} ];
const john = people.find(person => person.name === 'john');
console.log(john);
The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.
References
Array.prototype.some()
Array.prototype.forEach()
Array.prototype.map()
Array.prototype.filter()
Array.prototype.sort()
Spread syntax
Array.prototype.find()
You can use a for..of loop to loop over an array of objects.
for (let item of items) {
console.log(item); // Will display contents of the object inside the array
}
One of the best things about for..of loops is that they can iterate over more than just arrays. You can iterate over any type of iterable, including maps and objects. Make sure you use a transpiler or something like TypeScript if you need to support older browsers.
If you wanted to iterate over a map, the syntax is largely the same as the above, except it handles both the key and value.
for (const [key, value] of items) {
console.log(value);
}
I use for..of loops for pretty much every kind of iteration I do in Javascript. Furthermore, one of the coolest things is they also work with async/await as well.
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
Here's an example on how you can do it :)
var students = [{
name: "Mike",
track: "track-a",
achievements: 23,
points: 400,
},
{
name: "james",
track: "track-a",
achievements: 2,
points: 21,
},
]
students.forEach(myFunction);
function myFunction(item, index) {
for (var key in item) {
console.log(item[key])
}
}
Looping through an array of objects is a pretty fundamental functionality. This is what works for me.
var person = [];
person[0] = {
firstName: "John",
lastName: "Doe",
age: 60
};
var i, item;
for (i = 0; i < person.length; i++) {
for (item in person[i]) {
document.write(item + ": " + person[i][item] + "<br>");
}
}
It's really simple using the forEach method since ES5+. You can directly change each property of each object in your array.
myArray.forEach(function (arrayElem){
arrayElem = newPropertyValue;
});
If you want to access a specific property on each object:
myArray.forEach(function (arrayElem){
arrayElem.nameOfYourProperty = newPropertyValue;
});
myArray[j.x] is logically incorrect.
Use (myArray[j].x); instead
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
const jobs = [
{
name: "sipher",
family: "sipherplus",
job: "Devops"
},
{
name: "john",
family: "Doe",
job: "Devops"
},
{
name: "jim",
family: "smith",
job: "Devops"
}
];
const txt =
` <ul>
${jobs.map(job => `<li>${job.name} ${job.family} -> ${job.job}</li>`).join('')}
</ul>`
;
document.body.innerHTML = txt;
Be careful about the back Ticks (`)
this.data = [{name:"Rajiv", city:"Deoria"},{name:"Babbi", city:"Salempr"},{name:"Brijesh", city:"GKP"}];
for(const n of this.data) {
console.log(n.name)
}
This would work. Looping thorough array(yourArray) . Then loop through direct properties of each object (eachObj) .
yourArray.forEach( function (eachObj){
for (var key in eachObj) {
if (eachObj.hasOwnProperty(key)){
console.log(key,eachObj[key]);
}
}
});
Accepted answer uses normal function. So posting the same code with slight modification using arrow function on forEach
yourArray.forEach(arrayItem => {
var x = arrayItem.prop1 + 2;
console.log(x);
});
Also in $.each you can use arrow function like below
$.each(array, (item, index) => {
console.log(index, item);
});
Here's another way of iterating through an array of objects (you need to include jQuery library in your document for these).
$.each(array, function(element) {
// do some operations with each element...
});
Array object iteration, using jQuery,
(use the second parameter to print the string).
$.each(array, function(index, item) {
console.log(index, item);
});
var c = {
myProperty: [
{ name: 'this' },
{ name: 'can' },
{ name: 'get' },
{ name: 'crazy' }
]
};
c.myProperty.forEach(function(myProperty_element) {
var x = myProperty_element.name;
console.log('the name of the member is : ' + x);
})
This is one of the ways how I was able to achieve it.
I want to loop and deconstruction assignment at the same time, so code like this: config.map(({ text, callback })=>add_btn({ text, callback }))
This might help somebody. Maybe it's a bug in Node.
var arr = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
var c = 0;
This doesn't work:
while (arr[c].name) { c++; } // TypeError: Cannot read property 'name' of undefined
But this works...
while (arr[c]) { c++; } // Inside the loop arr[c].name works as expected.
This works too...
while ((arr[c]) && (arr[c].name)) { c++; }
BUT simply reversing the order does not work. I'm guessing there's some kind of internal optimization here that breaks Node.
while ((arr[c].name) && (arr[c])) { c++; }
Error says the array is undefined, but it's not :-/ Node v11.15.0
I know it's been long but for anyone else encountering this issue, my problem is that I was looping through an array of arrays containing only one array. Like this:
// array snippet (returned from here)
} else {
callback([results])
}
And I was using the array like this
for(const result of results){
console.log(result.x)
}
As you can see, the array I wanted to iterate over was actually inside another array. removing the square brackets helped. Node JS and MySQL.
I managed to reduce and combine my Price Amount Object with this:
stooges = [{Price: 1.2, Amount: 40}, {Price: 1.3, Amount: 50}, {Price: 1.2, Amount: 60}];
inputarray = _.map _.groupBy(stooges, 'Price'), (v, k) ->
{ Price: k
Amount : _.reduce(v, ((m, i) -> m + i['Amount']), 0)}
console.log(inputarray)
Creates the following
[Object { Price="1.2", Amount=100}, Object { Price="1.3", Amount=50}]
But maybe the grouping is to much. anyhow i try to end up like this
[ { 1.2 : 100 } , { 1.3 : 50 } ]
With the Price as Key and the Amount as Value.
Damn i suck at this.
Try this:
_.map(_.groupBy(stooges, 'Price'), function(v, k){
var obj = {};
obj[k] = _.reduce(v, function(m, i){ return m + i['Amount'] }, 0);
return obj;
})
It returns the following:
[{ "1.2": 100 }, { "1.3": 50 }]
Edit: I'm not sure it's all that helpful to return an array. If you're using Lo-Dash instead of Underscore (which I recommend you do), you can use this instead which will return a single object with all the prices as keys to the total amount:
_(stooges).groupBy('Price').mapValues(function(stooge){
return _(stooge).pluck('Amount').reduce(function(total, amount){
return total + amount;
})
}).value()
It returns the following:
{ "1.2": 100, "1.3": 50 }
result1 = _.pluck inputarray,'Price'
result2 = _.pluck inputarray,'Amount'
boo = _.object(result1,result2);
Thanks got it now its not that elegant as yours!
I want to cycle through the objects contained in an array and change the properties of each one. If I do this:
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j]);
}
The console should bring up every object in the array, right? But in fact it only displays the first object. if I console log the array outside of the loop, all the objects appear so there's definitely more in there.
Anyway, here's the next problem. How do I access, for example Object1.x in the array, using the loop?
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j.x]);
}
This returns "undefined." Again the console log outside the loop tells me that the objects all have values for "x". How do I access these properties in the loop?
I was recommended elsewhere to use separate arrays for each of the properties, but I want to make sure I've exhausted this avenue first.
Thank you!
Use forEach its a built-in array function. Array.forEach():
yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});
Some use cases of looping through an array in the functional programming way in JavaScript:
1. Just loop through an array
const myArray = [{x:100}, {x:200}, {x:300}];
myArray.forEach((element, index, array) => {
console.log(element.x); // 100, 200, 300
console.log(index); // 0, 1, 2
console.log(array); // same myArray object 3 times
});
Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.
2. Check if any of the elements in an array pass a test
const people = [
{name: 'John', age: 23},
{name: 'Andrew', age: 3},
{name: 'Peter', age: 8},
{name: 'Hanna', age: 14},
{name: 'Adam', age: 37}];
const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true
3. Transform to a new array
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]
Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.
4. Sum up a particular property, and calculate its average
const myArray = [{x:100}, {x:200}, {x:300}];
const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300
const average = sum / myArray.length;
console.log(average); // 200
5. Create a new array based on the original but without modifying it
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => {
return {
...element,
x: element.x * 2
};
});
console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]
6. Count the number of each category
const people = [
{name: 'John', group: 'A'},
{name: 'Andrew', group: 'C'},
{name: 'Peter', group: 'A'},
{name: 'James', group: 'B'},
{name: 'Hanna', group: 'A'},
{name: 'Adam', group: 'B'}];
const groupInfo = people.reduce((groups, person) => {
const {A = 0, B = 0, C = 0} = groups;
if (person.group === 'A') {
return {...groups, A: A + 1};
} else if (person.group === 'B') {
return {...groups, B: B + 1};
} else {
return {...groups, C: C + 1};
}
}, {});
console.log(groupInfo); // {A: 3, C: 1, B: 2}
7. Retrieve a subset of an array based on particular criteria
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}]
Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
8. Sort an array
const people = [
{ name: "John", age: 21 },
{ name: "Peter", age: 31 },
{ name: "Andrew", age: 29 },
{ name: "Thomas", age: 25 }
];
let sortByAge = people.sort(function (p1, p2) {
return p1.age - p2.age;
});
console.log(sortByAge);
9. Find an element in an array
const people = [ {name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67} ];
const john = people.find(person => person.name === 'john');
console.log(john);
The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.
References
Array.prototype.some()
Array.prototype.forEach()
Array.prototype.map()
Array.prototype.filter()
Array.prototype.sort()
Spread syntax
Array.prototype.find()
You can use a for..of loop to loop over an array of objects.
for (let item of items) {
console.log(item); // Will display contents of the object inside the array
}
One of the best things about for..of loops is that they can iterate over more than just arrays. You can iterate over any type of iterable, including maps and objects. Make sure you use a transpiler or something like TypeScript if you need to support older browsers.
If you wanted to iterate over a map, the syntax is largely the same as the above, except it handles both the key and value.
for (const [key, value] of items) {
console.log(value);
}
I use for..of loops for pretty much every kind of iteration I do in Javascript. Furthermore, one of the coolest things is they also work with async/await as well.
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
Here's an example on how you can do it :)
var students = [{
name: "Mike",
track: "track-a",
achievements: 23,
points: 400,
},
{
name: "james",
track: "track-a",
achievements: 2,
points: 21,
},
]
students.forEach(myFunction);
function myFunction(item, index) {
for (var key in item) {
console.log(item[key])
}
}
Looping through an array of objects is a pretty fundamental functionality. This is what works for me.
var person = [];
person[0] = {
firstName: "John",
lastName: "Doe",
age: 60
};
var i, item;
for (i = 0; i < person.length; i++) {
for (item in person[i]) {
document.write(item + ": " + person[i][item] + "<br>");
}
}
It's really simple using the forEach method since ES5+. You can directly change each property of each object in your array.
myArray.forEach(function (arrayElem){
arrayElem = newPropertyValue;
});
If you want to access a specific property on each object:
myArray.forEach(function (arrayElem){
arrayElem.nameOfYourProperty = newPropertyValue;
});
myArray[j.x] is logically incorrect.
Use (myArray[j].x); instead
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
const jobs = [
{
name: "sipher",
family: "sipherplus",
job: "Devops"
},
{
name: "john",
family: "Doe",
job: "Devops"
},
{
name: "jim",
family: "smith",
job: "Devops"
}
];
const txt =
` <ul>
${jobs.map(job => `<li>${job.name} ${job.family} -> ${job.job}</li>`).join('')}
</ul>`
;
document.body.innerHTML = txt;
Be careful about the back Ticks (`)
this.data = [{name:"Rajiv", city:"Deoria"},{name:"Babbi", city:"Salempr"},{name:"Brijesh", city:"GKP"}];
for(const n of this.data) {
console.log(n.name)
}
This would work. Looping thorough array(yourArray) . Then loop through direct properties of each object (eachObj) .
yourArray.forEach( function (eachObj){
for (var key in eachObj) {
if (eachObj.hasOwnProperty(key)){
console.log(key,eachObj[key]);
}
}
});
Accepted answer uses normal function. So posting the same code with slight modification using arrow function on forEach
yourArray.forEach(arrayItem => {
var x = arrayItem.prop1 + 2;
console.log(x);
});
Also in $.each you can use arrow function like below
$.each(array, (item, index) => {
console.log(index, item);
});
Here's another way of iterating through an array of objects (you need to include jQuery library in your document for these).
$.each(array, function(element) {
// do some operations with each element...
});
Array object iteration, using jQuery,
(use the second parameter to print the string).
$.each(array, function(index, item) {
console.log(index, item);
});
var c = {
myProperty: [
{ name: 'this' },
{ name: 'can' },
{ name: 'get' },
{ name: 'crazy' }
]
};
c.myProperty.forEach(function(myProperty_element) {
var x = myProperty_element.name;
console.log('the name of the member is : ' + x);
})
This is one of the ways how I was able to achieve it.
I want to loop and deconstruction assignment at the same time, so code like this: config.map(({ text, callback })=>add_btn({ text, callback }))
This might help somebody. Maybe it's a bug in Node.
var arr = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
var c = 0;
This doesn't work:
while (arr[c].name) { c++; } // TypeError: Cannot read property 'name' of undefined
But this works...
while (arr[c]) { c++; } // Inside the loop arr[c].name works as expected.
This works too...
while ((arr[c]) && (arr[c].name)) { c++; }
BUT simply reversing the order does not work. I'm guessing there's some kind of internal optimization here that breaks Node.
while ((arr[c].name) && (arr[c])) { c++; }
Error says the array is undefined, but it's not :-/ Node v11.15.0
I know it's been long but for anyone else encountering this issue, my problem is that I was looping through an array of arrays containing only one array. Like this:
// array snippet (returned from here)
} else {
callback([results])
}
And I was using the array like this
for(const result of results){
console.log(result.x)
}
As you can see, the array I wanted to iterate over was actually inside another array. removing the square brackets helped. Node JS and MySQL.