Question:
How can you retrieve values from a nested JavaScript object or array using a string path that specifies the property or element names?
Answer:
Using pure JavaScript, you can achieve this with the following helper function:
Object.byString = function (o, s) { s = s.replace(/\[(\w+)\]/g, "."); // convert indexes to properties s = s.replace(/^\./, ""); // strip a leading dot var a = s.split("."); for (var i = 0, n = a.length; i < n; ++i) { var k = a[i]; if (k in o) { o = o[k]; } else { return; } } return o; };
This function takes two parameters: the object or array to navigate, and a string path representing the properties or elements to retrieve.
Example:
Let's use the provided example data structure:
var someObject = { part1: { name: "Part 1", size: "20", qty: "50", }, part2: { name: "Part 2", size: "15", qty: "60", }, part3: [ { name: "Part 3A", size: "10", qty: "20", }, { name: "Part 3B", size: "5", qty: "20", }, { name: "Part 3C", size: "7.5", qty: "20", }, ], };
To access the "name" property of the "part1" object using the string path, you would use:
var part1name = Object.byString(someObject, "part1.name"); console.log(part1name); // Output: Part 1
Similarly, to retrieve the "qty" property of the "part2" object:
var part2quantity = Object.byString(someObject, "part2.qty"); console.log(part2quantity); // Output: 60
And to access the "name" property of the first element in the "part3" array:
var part3name1 = Object.byString(someObject, "part3[0].name"); console.log(part3name1); // Output: Part 3A
Note: It's important to prefix numerical array indexes with square brackets ("[") and suffix them with square brackets and a period ("]."). This ensures that the function correctly accesses array elements.
The above is the detailed content of How to Access Nested JavaScript Object/Array Values Using String Paths?. For more information, please follow other related articles on the PHP Chinese website!