Having trouble finding value with for-in loop - javascript

I am attempting to loop through this array's objects elements and return 'gotcha, bill' when the 'for in' loop finds the value 'bill'. However, it only seems to return 'not him' four times. I've skimmed over it several times and I'm not sure what I am missing. This is my first time using a for in loop, so I could be misunderstanding how it works.
Any help would be appreciated!
var names = [{name: 'steven', age: 22}, {name: 'bill', age: 13}];
function findBill(array) {
for(let i = 0; i < array.length; i++) {
for(let key in array[i]) {
if(key === 'bill') {
return console.log('gotcha, bill');
} else {
console.log('not him');
}
}
}
}
findBill(names)

for..in iterates over an object's keys. Since bill is a value, not a key, the (key === 'bill') test will never evaluate to true.
If you wanted to iterate over the object's values instead, use Object.values, and since it sounds like you want to find the bill object, you can use .find:
var names = [{name: 'steven', age: 22}, {name: 'bill', age: 13}];
function findBill(array) {
return array.find((obj) => (
Object.values(obj).includes('bill')
))
};
console.log(findBill(names))
If you know in advance that the value will be in the name property, then just test that property, rather than using Object.values:
var names = [{name: 'steven', age: 22}, {name: 'bill', age: 13}];
function findBill(array) {
return array.find((obj) => (
obj.name === 'bill'
))
};
console.log(findBill(names))

Here. I changed your for loop to forEach but that is not the main thing that solves your problem. It is how you access the object's property. I use forEach because it will be easier (for me) to get the desired data from the object.
var names = [{name: 'steven', age: 22}, {name: 'bill', age: 13}];
function findBill(array) {
array.forEach(function(person){
if(person.name === 'bill') {
return console.log('gotcha, bill');
} else {
console.log('not him');
}
});
}
findBill(names)
And this is how it should be if you insist on using for loop.
var names = [{name: 'steven', age: 22}, {name: 'bill', age: 13}];
function findBill(array) {
for(let i = 0; i < array.length; i++) {
if(array[i].name === 'bill') {
return console.log('gotcha, bill');
} else {
console.log('not him');
}
}
}
findBill(names)

key is exactly that--the keys of each object, namely, name or age. You need to actually index into the array at the correct index, then access the value for the key you're inspecting in the loop with if (array[i][key] === 'bill').
Here's a working example:
var names = [{name: 'steven', age: 22}, {name: 'bill', age: 13}];
function findBill(array) {
for(let i = 0; i < array.length; i++) {
for(let key in array[i]) {
if(array[i][key] === 'bill') {
return console.log('gotcha, bill');
} else {
console.log('not him');
}
}
}
}
findBill(names);
However, the extra loop isn't necessary and causes logic errors because you might have some other key, say, buffalo that happens to have the value "bill" and you'll wind up with a false positive. You know the key, so you can simply search the array for any object with the matching value for that key:
var names = [{name: 'steven', age: 22}, {name: 'bill', age: 13}];
console.log(names.find(e => e.name === "bill"));
Lastly, I recommend avoiding console.log in functions, which is a side effect that limits reusability. console.log returns undefined after printing, so it's misleading to return this, even in simple or contrived examples.

You don't need two loops for this. In fact you can use the Array.find() method to find the object you need and do with it what you need:
const people = [{name: 'steven', age: 22}, {name: 'bill', age: 13}];
const findByName = (data, name) => data.find(cur => cur.name === name);
const Bill = findByName(people, 'bill');
if (Bill === null) { console.log(`could not find bill`); }
else { console.log(`bill is ${Bill.age} years old`); }

Related

Can't access object's properties by argument of a function

Why array[i].key (where key === "surname") within the function doesn't work,
meanwhile array[i].surname works perfectly?
let objects = [
{ name: 'Jack', surname: 'Jackson' },
{ name: 'Ivar', surname: 'Bjornsson' },
{ name: 'John', surname: 'Mickelson' }
];
function sort (array, key) {
for (let i = 0; i < array.length; i++) {
console.log(array[i].key)// Somehow the "key", which is equal to "surname" doesn't work;
// here will be undefined;
console.log(array[i].surname)//But here writing 'surname' directly works fine;
// the correct answer will be there;
console.log(key)// However, key === surname
}
}
sort(objects, 'surname');
You have to access the property with square brackets:
let objects = [
{ name: 'Jack', surname: 'Jackson' },
{ name: 'Ivar', surname: 'Bjornsson' },
{ name: 'John', surname: 'Mickelson' }
];
function sort (array, key) {
for (let i = 0; i < array.length; i++) {
console.log(array[i][key])// Somehow the "key", which is equal to "surname" doesn't work;
// here will be undefined;
console.log(array[i].surname)//But here writing 'surname' directly works fine;
// the correct answer will be there;
console.log(key)// However, key === surname
}
}
sort(objects, 'surname');
This
array[i].key
is equivalent to
array[i]['key']

indexOf method for array of objects in Javascript

I have array of objets like:
var MyArray = [] ,
Person = {},
[
{
name: 'John',
surname: 'Smith',
age: '22'
},
{
name: 'Jesica',
surname: 'Garou',
age: '31'
},
{
name: 'Max',
surname: 'Jolie',
age: '50'
}
]
I want to check , if my data has name 'John' that don't add new person , if not , then add new person with name 'John' and etc.
Thanks in advance .
You could deal with it using Array#find. I assume that you want to mutate your original array.
let arr = [{
name: 'Jesica',
surname: 'Garou',
age: '31'
},
{
name: 'Max',
surname: 'Jolie',
age: '50'
}
];
const obj = {
name: 'John',
surname: 'Smith',
age: '22'
};
const ensure = ({ name, ...z }) => {
if (!arr.find(v => v.name === name)) {
arr.push({ name, ...z });
}
}
ensure(obj);
console.log(arr);
You can use map but you have to know that map iterates through all elements in the array, whereas findIndex returns the first element index that equals the condition and stops the loop.
var MyArray = [
{
name: 'John',
surname: 'Smith',
age: '22'
},
{
name: 'Jesica',
surname: 'Garou',
age: '31'
},
{
name: 'Max',
surname: 'Jolie',
age: '50'
}
];
if(MyArray.findIndex(index => index.name === "John") > -1)
console.log("Found!");
else
console.log("Not found!");
To check if a name already exists in an array, you can make use of array.some function. It will check if name provided already exits or not.
If not then you can write the code to push the object in the array.
I have used the sample names John and Anne. For John, the function isAlreadyPresent returns true. For Anne, it returns false.
let arr = [
{
name: 'John',
surname: 'Smith',
age: '22'
},
{
name: 'Jesica',
surname: 'Garou',
age: '31'
},
{
name: 'Max',
surname: 'Jolie',
age: '50'
}
];
function isAlreadyPresent(name) {
return arr.some(a => a.name === name );
}
console.log('John already exists?',isAlreadyPresent('John'));
console.log('Anne already exists?',isAlreadyPresent('Anne'));
Maybe a name Map could be useful:
var byNam e =new Map(myArray.map(el=>[el.name,el]));
So you can easily do:
if (byName.has("John")){
alert("already exists");
} else {
var obj = { name: "John" };
Map.set(obj.name,obj);
myArray.push(obj);
}
The upper can be achieved with a Set also, but you may also want to do this:
byName.get("John").age=15;
You'll need to loop through all of the objects and check each of their name values. At worst runs in O(n) time.
For example, to check if "John" is a name in the array:
var inArray = false; // Have we found the name in the array yet?
for (var i = 0; i < MyArray.length; i++) { // Loop through the array of objects
if (MyArray[i].name=="John") { // If the name field is equal to "John"
inArray = true; // Name is in the array
break; // Exit the loop
}
}
var searchTerm = "John",
index = -1;
for(var i = 0, len = MyArray.length; i < len; i++) {
if (MyArray[i].name === searchTerm) {
alert("matched string");
index = i;
break;
}
}
You can make a search function like this that:
const index = (array, name) => {
// Search for the string "name" in your array
for (let i in array){
// Look at every element in the array, if an element has the
// corresponding name, return its index
if (array[i].name === name) return i;
}
return -1;
// If you found nothing, return -1
}
let position = index(myArray, "John");
Traditionally we use a constructor to build many similar objects. However, how that is OOP and is out of the scope of what you are asking.
Here we can use a for... in loop to iterate though MyArray, and check that each object does not include the name John.
function addJohn () {
for (let iterator in MyArray) { // You can also use for... of, but it will break in Node.
if (MyArray[iterator].name == "John") {return}; //You can also replace the string with a variable name to check that all objects do not have the variable in them.
else continue;
}
// you can now put in your new object here.
}

Loop through an array of objects and sort them

I have an array containing some objects and I am trying to loop through it where I have data stored in the following order:
firstName: Alice
lastName: Wonderland
age:12
I am trying to loop, then to sort it in descending order where age: value should be in first position then > lastName: Wonderland comes and lastly firstName.
Here is my code until this moment
var data = {
example1: [{
firstName: 'Alice',
lastName: 'Wonderland',
age: 12
}],
example2: [{
firstName: 'Thomas',
lastName: 'Mathison',
age: 14
}],
example3: [{
firstName: 'David',
lastName: 'Jacobsen',
age: 18
}]
};
for (var key in data) {
var arr = data[key];
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
console.log(prop + ': ' + obj[prop]);
}
}
}
}
I want to achieve the reverse order (descending) when I output the result in the console.log();:
age: 12,
lastName: 'Wonderland',
firstName: 'Alice'
age:14,
lastName: 'Mathison',
firstName: 'Thomas'
age:18,
lastName: 'Jacobsen',
firstName: 'David'
I am not sure about the sort function behavior. How should it work during the loop?
Any suggestions?
var data = {
example1: [{
firstName: 'Alice',
lastName: 'Wonderland',
age: 12
}],
example2: [{
firstName: 'Thomas',
lastName: 'Mathison',
age: 14
}],
example3: [{
firstName: 'David',
lastName: 'Jacobsen',
age: 18
}]
};
var objectArray=[];
for (var key in data) {
var arr = data[key];
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
objectArray.push(obj);
}
}
objectArray.sort(function(element1,element2){
return element2.age - element1.age
}); //now iterate over the array it is sorted in descending order
Sorting arrays of non-primitive data types (custom objects and data structures like in your case) require two steps. It's quite straightforward so follow along.
First you need to create a function capable of comparing two objects of your custom data structure according to your desired criteria.
Second, you provide this decision function to a sort function along with your array and it will use it to sort the array for you. Lets do it for your case:
First the compare function, a and b are objects from your custom structure. returning 1 means object a is "bigger", returning -1 means b is "bigger", returning 0 means that, according to your criteria, both are equal in "size". The order of the if statements bellow is naturally important and reflects the priorities you described:
age takes priority over names and last-name over first-name.
function compare_people(a, b) {
if (a.age < b.age) {
return -1;
}
if (a.age > b.age) {
return 1;
}
if (a.lastName < b.lastName) {
return -1;
}
if (a.lastName > b.lastName) {
return 1;
}
if (a.firstName< b.firstName) {
return -1;
}
if (a.firstName> b.firstName) {
return 1;
}
return 0;
}
Now all you have to do is provide your criteria and array to javascript's sort function. In your case objects are stored inside the data array, so you do:
data.sort(compare_people);
Done, array sorted!
Here you can study the concept more in depth https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Good luck.
Apparently the question is not clear enough, people keep giving you sorting algorithms which I understand it is not what you are looking for, you want to change the internal order of the properties (which makes no sense, they have no 'order' they are part of a map, in any case, here is what I would do:
var data = {
example1: [{
firstName: 'Alice',
lastName: 'Wonderland',
age: 12
}],
example2: [{
firstName: 'Thomas',
lastName: 'Mathison',
age: 14
}],
example3: [{
firstName: 'David',
lastName: 'Jacobsen',
age: 18
}]
};
for (var key in data) {
var arr = data[key];
var newArr = [];
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
newArr.push({
age: obj.age,
firstName: obj.firstName,
lastName: obj.lastName
})
}
data[key] = newArr;
}
But again, what you are trying to do makes no sense, or at least according to the description.
Use [].unshift() method
var result = [];
for (var key in data) {
var arr = data[key];
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
result.unshift(prop + ': ' + obj[prop])
}
}
}
}
console.log(result)
here is demo https://plnkr.co/edit/N4Zt28zh0A3MpwoOrzmZ?p=preview

get values from list of objects in javascript [duplicate]

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.

How to loop through an array containing objects and access their properties

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.

Categories

Resources