Isaac F Isaac F - 2 months ago 6
Javascript Question

How can iterate this Object in JavaScript

I have this Object:

var foo =
[
{"na":[{"title":"Plaza nl1","img":"algo_nl1"},{"title":"Plaza nl2","img":"algo_nl2"}]},
{"ne":[{"title":"Plaza C1","img":"algo"},{"title":"Plaza C2","img":"algo 2"}]}
];


through an event, I get the string "na" or "ne". I want obtain the object "na" or "ne" any idea?...

For example, with the string "na" obtains:

{"na":[{"title":"Plaza nl1","img":"algo_nl1"},{"title":"Plaza nl2","img":"algo_nl2"}]}


Thanks!

Answer

var foo = [
    {
        "na": [
                {
                    "title": "Plaza nl1",
                    "img": "algo_nl1"
                },
                {
                    "title": "Plaza nl2",
                    "img": "algo_nl2"
                }
        ]
    },
    {
        "ne": [
            {
                "title": "Plaza C1",
                "img": "algo"
            },
            {
                "title": "Plaza C2",
                "img": "algo 2"
            }
        ]
    }
];

console.log('na');
console.log(foo[0]['na']);
console.log('ne');
console.log(foo[1]['ne']);

console.log('---');

for (var f in foo) {
  for (var v in foo[f]) {
    console.log(v);
    console.log(foo[f][v]);
  }
}

function getElement(key) {
    for (var f in foo) {
        for (var v in foo[f]) {
            if (v == key) {
                return foo[f][v];
            }
        }
    }
}

console.log('---');

console.log('na');
console.log(getElement('na'));
console.log('ne');
console.log(getElement('ne'));