Reputation: 1829
I have JSON/JS like this that populates data:
var settingDefs = [];
settingDefs.push({
name:'responses', label:'Responses', type:'aeditor',
defaultValue: Object.toJSON([
{"id":"1", "name":"Bob", "text":"Is here"},
{"id":"2", "name":"James", "text":"Online"},
])
});
How would I retrieve an entry say if I had "1" and I wanted to lookup using that "1" to retrieve the name/text for that entry (entry 1)?
Upvotes: 0
Views: 116
Reputation: 9361
Not sure why you need Object.toJSON here. I would do something like this:
var settingDefs = [];
settingDefs.push({
name:'responses', label:'Responses', type:'aeditor',
defaultValue: [
{"id":"1", "name":"Bob", "text":"Is here"},
{"id":"2", "name":"James", "text":"Online"},
]
});
var valueWithId1 = $.grep(settingDefs[0].defaultValue, function(el){return el.id === "1";})[0]
I use jQuery.grep here. If you don't use jQuery or other libraries with similar function you will need to iterate through the array manually, as others have suggested
Upvotes: 0
Reputation: 23316
It's unclear from your question what that entry
refers to.
If the JSON de-serialized object looks like this:
var foo = [
{"id":"1", "name":"Bob", "text":"Is here"},
{"id":"2", "name":"James", "text":"Online"},
]
Then you have an array of objects where each object has a property id
with a string value (that happens to be a number).
Therefore, you need to iterate over the array and test the value of the id
property:
var findObjById = function(arr, idToFind) {
for(i = 0; i < arr.length; i++) {
if(arr[i].id === idToFind) return arr[i];
}
}
var obj = findObjById(foo, "1");
Upvotes: 1
Reputation: 156374
Assuming that each defaultValue property will be an Array and not a JSON string - you should iterate through the settingDefs array and return all (or maybe just the first?) entry in the defaultValue property whose id matches the one you have. Something like this:
function lookupValueById(sds, id) {
for (var i=0; i<sds.length; i++) {
for (var j=0; j<sds[i].defaultValue.length; j++) {
var el = sds[i].defaultValue[j];
if (el.id == id) return el;
}
}
return null;
}
lookupValueById(settingDefs, 1); // => {id:'1', name:'Bob', text:'Is Here'}
Upvotes: 1