How to loop through a plain JavaScript object with the objects as members
for (var key in validation_messages) {
// skip loop if the property is from prototype
if (!validation_messages.hasOwnProperty(key)) continue;
var obj = validation_messages[key];
for (var prop in obj) {
// skip loop if the property is from prototype
if (!obj.hasOwnProperty(prop)) continue;
// your code
alert(prop + " = " + obj[prop]);
}
}
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]);
}
}
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]]);
}
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)
Looping through an object and changing all values
try
var superSecret = function(spy){
Object.keys(spy).forEach(function(key){ spy[key] = "redacted" });
return spy;
}
Loop through object of objects and arrays
You can easily do this recursively.
function recurse(node, level=0) {
if (node == null) return; // Check for null, exit
console.log(node.id == null ? 'root' : node.id); // Print the ID
if (node.children) node.children.forEach(child => recurse(child, level + 1)); // Hand off to children
}
Example Output from code below.
root
↓ ID: 9737ea0a-fa6f-42e1-bf16-a10af80e4d50
↳ Name: Domain 1
↓ ID: e06d1940-b480-48e2-8e1a-2fe2a3910dfd
↳ Name: Sub domain 1
↓ ID: 30995e1e-7195-4d01-85bf-c621398796cc
↳ Name: sub domain 1 - 2
↳ ID: 2969e48d-615e-4774-b92e-cbce768503ff
↳ Name: Criteria 1
↳ Type: Yes/NO
↳ Importance: 3
↓ ID: c5b36f02-e765-4d93-970c-6faca94c28c1
↳ Name: sub domain 2
↳ ID: 6807ea4f-fb14-4d68-98f4-b3bf4c601e5c
↳ Name: Criteria 2
↳ Type: 5
↳ Importance: 1
const data = loadData();
recurse(data);
function recurse(node, level=0) {
if (node == null) return;
let symbol = node.isCriteria ? '↳' : '↓';
let paddingOuter = ''.padStart((level - 1) * 2, ' ');
let paddingInner = ''.padStart((level + 1) * 2, ' ');
console.log(node.id == null ? 'root' : paddingOuter + symbol + ' ID: ' + node.id);
if (node.name) console.log(paddingInner + '↳ Name: ' + node.name);
if (node.isCriteria) {
console.log(paddingInner + '↳ Type: ' + node.questionType);
console.log(paddingInner + '↳ Importance: ' + node.importance);
}
if (node.children) node.children.forEach(child => recurse(child, level + 1));
}
function loadData() {
return {
"children": [{
"id": "9737ea0a-fa6f-42e1-bf16-a10af80e4d50",
"isCriteria": false,
"name": "Domain 1",
"children": [{
"id": "e06d1940-b480-48e2-8e1a-2fe2a3910dfd",
"children": [{
"id": "30995e1e-7195-4d01-85bf-c621398796cc",
"children": [{
"id": "2969e48d-615e-4774-b92e-cbce768503ff",
"children": [
],
"isCriteria": true,
"name": "Criteria 1",
"questionType": "Yes/NO",
"importance": 3
}],
"isCriteria": false,
"name": "sub domain 1 - 2"
}],
"isCriteria": false,
"name": "Sub domain 1"
},
{
"id": "c5b36f02-e765-4d93-970c-6faca94c28c1",
"children": [{
"id": "6807ea4f-fb14-4d68-98f4-b3bf4c601e5c",
"children": [
],
"isCriteria": true,
"name": "Criteria 2",
"questionType": "5",
"importance": "1"
}],
"isCriteria": false,
"name": "sub domain 2"
}
]
}]
};
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Loop through multiple objects and get similar key values in new object
You can use the function below. Just pass the array
you want to sort.
function dataSorter(dataArr) {
const data = {};
for (const item in dataArr[0]) data[item] = [];
for (let i = 0; i < dataArr.length; i++) {
for (const item in dataArr[i]) {
data[item].push(dataArr[i][item]);
}
}
return data;
}
/* Example Below */
let newDats = [{
ID: 1,
Name: "Ahmed",
Age: 17,
Score: 84,
Absentee: 3
},
{
ID: 2,
Name: "Hassan",
Age: 15,
Score: 87,
Absentee: 2
},
{
ID: 3,
Name: "Aisha",
Age: 18,
Score: 86,
Absentee: 2
},
];
console.log(dataSorter(newDats));
.as-console-wrapper { max-height: 100% !important; top: 0; } /* Ignore this */
loop through nested object and change property
You can just loop over the value of mydata.language
with the help of forEach
and make show
as false
as:
Object.values(mydata.language).forEach((o) => o.show = false);
const mydata = {
message: 'Hello Vues!',
language: {
en: { show: false, displayname: 'English' },
ja: { show: true, displayname: 'Japanese' },
zh: { show: false, displayname: 'Chinese' },
},
};
Object.values(mydata.language).forEach((o) => o.show = false);
console.log(mydata);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related Topics
$(Document).Ready Equivalent Without Jquery
Persist Variables Between Page Loads
How to Merge Two Arrays in JavaScript and De-Duplicate Items
Why Does Calling React Setstate Method Not Mutate the State Immediately
Abort Ajax Requests Using Jquery
Iterate Through Object Properties
Google Maps Js API V3 - Simple Multiple Marker Example
Use of 'Prototype' Vs. 'This' in JavaScript
Safely Turning a Json String into an Object
Methods in Es6 Objects: Using Arrow Functions
When Should I Use a Return Statement in Es6 Arrow Functions
Why Is Settimeout(Fn, 0) Sometimes Useful
How to Make an Ajax Call Without Jquery
Use Dynamic Variable Names in JavaScript
Get Selected Text from a Drop-Down List (Select Box) Using Jquery