1. Iterating Over a JSON Object
To extract key-value pairs from a JSON Object, you can use the following methods:
Method 1: Using the for...in Loop (ES5 Standard)
The for...in loop iterates over all enumerable properties of an object.
var myJson = {
"element1": "hello",
"element2": 12,
"element3": true,
"element4": {
"subelement1": "one",
"subelement2": 2
}
};
for (var el in myJson) {
if (myJson.hasOwnProperty(el)) {
console.log("Element name: " + el +
", element value: " + myJson[el] +
", element type: " + typeof(myJson[el]));
}
}
Method 2: Using Object.keys() (ES5)
Returns an array of a given object's own property names, which can then be iterated using a standard loop.
var keys = Object.keys(myJson);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = myJson[key];
console.log("Key: " + key + ", Value: " + value);
}
2. Iterating Over a JSON Array
When working with JSON Arrays, you can use several looping mechanisms depending on your environment:
Method 1: Standard for Loop
The classic, highly performant loop that works across all JavaScript engines.
var propertiesPort = ['port1', 'port2', 'port3', 'port4', 'port5', 'port6', 'port7', 'port8', 'port9', 'port10', 'port11', 'port12'];
for (var i = 0; i < propertiesPort.length; i++) {
var portName = propertiesPort[i];
console.log("Port Name: " + portName);
}
Method 2: Using Array.prototype.forEach() (ES5)
Provides a clean functional style to iterate over array elements.
var propertiesPort = ['port1', 'port2', 'port3', 'port4'];
propertiesPort.forEach(function(portName, index) {
console.log("Index " + index + ": " + portName);
});
Method 3: Using for each...in (PTC ThingWorx / Rhino JS Engine)
In Rhino-based JavaScript engines (commonly used in PTC ThingWorx server-side scripts), the for each...in statement iterates directly over property values rather than keys.
// Iterating through ThingWorx InfoTable rows
for each (row in thingList.rows) {
// Each row is directly assigned to the 'row' variable
var thingName = row.name;
console.log("Thing Name: " + thingName);
}
Reference: ThingWorx
0 comments:
Post a Comment