0

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)?

2
  • 1
    Why are you using Object.toJSON? Commented Feb 9, 2012 at 19:47
  • Hmm I was following some code on community.spiceworks.com/plugin/9 Commented Feb 9, 2012 at 20:06

3 Answers 3

1

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'}
Sign up to request clarification or add additional context in comments.

1 Comment

should probably use === and pass the correct key, since there could be "1" and 1 as ids. Also 0 would match "0", False or "".
1

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");

1 Comment

Sorry, "that entry" as in the first entry (id 1).
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.