Iterating Through Object

How do I loop through or enumerate a JavaScript object?

You can use the for-in loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.

Here is the snippet:

var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};

for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}

iterating through object

You use a for..in loop for this. Be sure to check if the object owns the properties or all inherited properties are shown as well. An example is like this:

var obj = {a: 1, b: 2};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
}
}

Or if you need recursion to walk through all the properties:

var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);

How to iterate over a JavaScript object?

For iterating on keys of Arrays, Strings, or Objects, use for .. in :

for (let key in yourobject) {
console.log(key, yourobject[key]);
}

With ES6, if you need both keys and values simultaneously, do

for (let [key, value] of Object.entries(yourobject)) {
console.log(key, value);
}

To avoid logging inherited properties, check with hasOwnProperty :

for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) {
console.log(key, yourobject[key]);
}
}

You don't need to check hasOwnProperty when iterating on keys if you're using a simple object (for example one you made yourself with {}).

This MDN documentation explains more generally how to deal with objects and their properties.

If you want to do it "in chunks", the best is to extract the keys in an array. As the order isn't guaranteed, this is the proper way. In modern browsers, you can use

let keys = Object.keys(yourobject);

To be more compatible, you'd better do this :

 let keys = [];
for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) keys.push(key);
}

Then you can iterate on your properties by index: yourobject[keys[i]] :

for (let i=300; i < keys.length && i < 600; i++) { 
console.log(keys[i], yourobject[keys[i]]);
}

Using for in to iterate through objects values and return the highest value - Can I use it in the same way I would a for Loop

Traditional loop version, use variables greatest and its respective key, loop the object properties

const count = { '4': 1, '6': 1, '7': 1, '8': 1, '10': 2, '12': 3 };

let greatest = -Infinity;
let key;
for (let x in count) {
if (count[x] > greatest) {
key = x;
greatest = count[key];
}
}

console.log(key, greatest);

Loop through one object, and set its values from another object

You can use

var a = [obj1,obj2];
obj1 = Object.assign(...a);

let obj1 = {  name: 'obj 1',  id: 1,  color: "#fff",  pages: []}
let obj2 = { name: 'obj 2', id: 2, color: "#ddd"}var a = [obj1,obj2];obj1 = Object.assign(...a);console.log(obj1)

Iterate through object keys and values and return a new object

The number of elements in the expected array is equal to the number of keys in an array element so map over that, then run another simple map to generate the data array.

var out = Object.keys(data[0]).map(function(key) {
return {
label: key,
data: data.map(function(obj) {
return obj[key];
})
};
}

Iterate through array of objects and obtain a new array of object

You can do the following (Make sure you add checks for null/undefined references)

const data = [{
"title": "Release",
"projects": [{
"name": "Server",
"result": {
"success": 0,
"failure": 100
},
}]
},
{
"title": "Payments",
"projects": [{
"name": "Platform1",
"result": {
"success": 100,
"failure": 0
}
},
{
"name": "Platform2",
"result": {
"success": 50,
"failure": 50,
}
}
]
}
];

const result = data.flatMap(item =>
item.projects.map(project => ({
name: `${item.title}-${project.name}`,
success: project.result.success,
failure: project.result.failure
})));

console.log(result);

Loop through an object and only return certain keys together with their values

You can use a dictionary (array) to contain the keys you want to extract the properties for, and then reduce over the values with Object.entries to produce a new object matching only those entries included in the dictionary.

let a = {
"values": {
"myName": "Demo",
"active": "Y",
"myCode": "123456789",
"myType": 1,
"myGroups": [{
"myGroupName": "Group 1",
"myTypes": [{
"myTypeName": "323232",
"myTypeId": "1"
}]
},
{
"myGroupName": "Group 2",
"myTypes": [{
"myTypeName": "523232",
"myTypeId": "2"
}]
}
]
}
}

const arr = [ 'myName', 'active', 'myCode', 'myType' ];

const out = Object.entries(a.values).reduce((acc, [key, value]) => {
if (arr.includes(key)) acc[key] = value;
return acc;
}, {});

console.log(out);

How does one iterate through an object's property values in order to verify for some values (objects as well) each another specific property value?

Here's one way to look for a specific id. I consoled the object found and the length of that specific object. But I am being very unclear with what exactly you want.

let formik = {
"randomObj": 'something',
"values": {
flight1: {
'name': "flight1",
'timecreated': "sometime",
id: 548497984
},
flight2: {
'name': "flight2",
'timecreated': "sometime",
id: 548497982
},
flight3: {
'name': "flight3",
'timecreated': "sometime",
id: 548497989
},
flight4: {
'name': "flight4",
'timecreated': "sometime",
id: 548497981
}
},
attributes: 'null'
}

for (let key in formik.values) {
if (formik.values[key].id === 548497984) {
console.log(formik.values[key])
console.log("Length is: ", Object.keys(formik.values[key]).length)
break;
} else {
console.log("no matches")
}
}


Related Topics



Leave a reply



Submit