Created
November 15, 2016 07:06
-
-
Save netsi1964/549a67bb04c655bf7f6a5280dd9e0bab to your computer and use it in GitHub Desktop.
A basic JSON select function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// obj: JSON object | |
// selector: The path to the data you want to extract | |
function JSONselect(obj, selector) { | |
var levels = selector.split('.') | |
var object = obj; | |
levels.map(function(path) { | |
console.log(path) | |
object = object[path]; | |
}) | |
return object; | |
} | |
var myJson = { | |
name: "my object", | |
companies: [ | |
{ | |
name: "First company", | |
address: "Somewhere" | |
}, | |
{ | |
name: "Second company", | |
address: "Somewhere else" | |
} | |
], | |
age: 23 | |
}; | |
JSONselect(myJson, 'companies.0.name') // => "First company" | |
JSONselect(myJson, 'age') // => 23 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment