How to Loop Through an Array Containing Objects and Access Their Properties

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

Use forEach its a built-in array function. Array.forEach():

yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});

How can I loop through a JavaScript object array?

It appears you may just have missed the "messages" property in the data, so the loop is likely iterating the root Object rather than the Array:

for (var key in data.messages) {
var obj = data.messages[key];
// ...
}

Unless data was set to messages before the given snippet.

Though, you should consider changing that to a normal for loop for the Array:

for (var i = 0, l = data.messages.length; i < l; i++) {
var obj = data.messages[i];
// ...
}

How can loop over an array of objects and return true/false when at least one of the object's properties matches the properties of a test object

  • Using Array#map, iterate over the array
  • In every iteration, using Array#some, check if any of the combinations match the current object.
  • To do so, you can use Object#entries and Array#every to check a combination of properties matching the current object.

const array = [ { id: 1, size: '6M', color: 'Blue' }, { ld: 2, size: '2M', color: 'Yellow' }, { id: 3, size: '6M', color: 'Blue' } ];

const combinations = [ { "color": "Blue", "size": "6M" } ];

const matches = array.map(current =>
combinations.some(combination =>
Object.entries(combination).every(([key, value]) =>
current[key] === value
)
)
);

console.log(matches);

Loop through array and creating new arrays based on object properties

If I'm understanding your use case correctly, you should be able to do something like this:

private fun sortElements(input: List<Stuff>) = input.groupBy { it.name }

The idea here is that you take each element and put it into a Map where the key is the name value and the values are a List of your objects.

To give an example here, let's say I have a data class called Stuff:

data class Stuff(
val name: String,
val otherField: Int,
)

and test data that looks like this:

val userStuff = listOf(
Stuff("ball", 242),
Stuff("ball", 11),
Stuff("monkey", 848),
Stuff("monkey", 455),
Stuff("sausage", 836),
)

Calling the function above would give a result like this (this would be a Map<String, Stuff>, I just printed it out so you can see what's in there):

{
ball=[
Stuff(name=ball, otherField=242),
Stuff(name=ball, otherField=11)
],
monkey=[
Stuff(name=monkey, otherField=848),
Stuff(name=monkey, otherField=455)
],
sausage=[
Stuff(name=sausage, otherField=836)
]
}

Why can’t I access object properties in a for-in loop over an array of objects?

x is not a value It is a index like 0,1 ...14, you can use of for that or use data[x] inside in.

var data = [{        Name: "First Last",        ID: "12536723",        Status: "Member"    }, {        Name: "First Last",        ID: "12371238",        Status: "Member"    },    {        Name: "First Last",        ID: "12341228",        Status: "Member"    }]
for (var x in data) {
console.log(data[x].Name); //x is not a value It is a index like 0,1 ...14
}
for (var x of data) {
console.log(x.Name); // use of which prints x as object not index
}

How do I iterate over properties of an array (not the elements) in javascript?

I'm not aware of any way to directly iterate just the plain properties. But, you can construct a list of just the plain properties as follows:

ar.keys() gives you only the array element indexes (not plain properties)

Object.keys(ar) gives you all properties and array indexes.

So, you can start with all the properties and indexes and then filter out the ones that are array element indexes and be left with just the properties.

let ar = ['a', 'b', 'c'];
ar.prop1 = 'Hello';
ar.prop2 = 'world';

let arrayIndexes = new Set(Array.from(ar.keys(), i => "" + i));
console.log("arrayIndexes (converted to string)", Array.from(arrayIndexes));

let props = Object.keys(ar).filter(k => !arrayIndexes.has(k));
console.log("props", props);

How can I access the prop of the objects in an array with function, for loop and a conditional statement?

If the idea is to always compare with similarity, the method would be:

function team(name,prop){
for (let i = 0; i < details.length; i++){
if(details[i].first === name && details[i].similarity === prop){
return true;
} else {
return false;
}
}
}
team('Liverpool', 'EPL')

But if the property can be dynamic it would be:

function team(name, prop, cup){
for (let i = 0; i < details.length; i++){
if(details[i].first === name && details[i][prop] === cup){
return true;
} else {
return false;
}
}
}
team('Liverpool', 'similarity', 'EPL')

Another alternative is if you want to go through all the names, then it can be like this:

function team(name,prop){
for (let i = 0; i < details.length; i++){
const teams = Object.entries(details[i])
const similarity = details[i].similarity;

for (let j = 0; j < teams.length; j++){
if (teams[j][1] === name && similarity === prop){
return true;
}
}

}
return false;
}
team('Man City', 'EPL')

Hope this helps.

TypeScript How To Loop Through Array Of Objects

Thank you everyone for your useful comments!

I got it working with the following code:

onSubmit(form:NgForm)
{
this.service.postReportData().subscribe(
res => {
this.retrievedData = res;

this.retrievedData.reportData.forEach(function (item) {
console.log(item);
console.log(item.ProductName);
console.log(item.AverageQuantityOrdered);
});

},
err => {
console.log(err);
}
);

}

Since reportData contained the array of objects I had to loop through that and not retrievedData.

Once again thanks to everyone, I appreciate the help!



Related Topics



Leave a reply



Submit