0

I am trying to fetch the value of the nested objects without using it's key. Like for example if I have a object like

var a = {"key" : "100"}

I don't want to use a.key, to get the result, though i have nested objects, it is becoming difficult for me to fetch the value this is what I have tried:

var Obj = [{"ghi":{"content":"abc"}},{"def":{"imgURL":"test.png"}},{"abc":{"key":"001"}},{"ghi":{"content":"abc"}},{"def":{"imgURL":"test.png"}},{"abc":{"key":"001"}}]

for(var key in Obj){
 abc = Obj[key]
 for(var j in abc){
  def = abc[key]
 }
}

So i need the values of all the objects, without using the key directly.

shu
  • 1,938
  • 10
  • 19

1 Answers1

0

Maybe this helps

function getValues(array, key) {
    var result = [];
    array.forEach(function (a) {
        a[key] && result.push(a[key]);
    });
    return result;
}

var array = [{ "ghi": { "content": "abc" } }, { "def": { "imgURL": "test.png" } }, { "abc": { "key": "001" } }, { "ghi": { "content": "abc" } }, { "def": { "imgURL": "test.png" } }, { "abc": { "key": "001" } }];

document.write('<pre>' + JSON.stringify(getValues(array, 'ghi'), 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392