You can build yourself either an object or (in ES2015) a Map
:
Here's an ES5 example using an object:
var map = Object.create(null);
data.level1.level2.forEach(function(entry) {
Object.keys(entry).forEach(function(key) {
map[key] = entry;
});
});
Live example:
var data = {
"level1": {
"level2": [{
"product1": [
"item1",
"item2"
]
}, {
"product2": [
"item1",
"item2"
]
}, {
"product3": [
"item5",
"item6"
]
}]
}
};
var map = Object.create(null);
data.level1.level2.forEach(function(entry) {
Object.keys(entry).forEach(function(key) {
map[key] = entry;
});
});
var name = "product2";
console.log(map[name]);
We create the object (map
) using Object.create(null)
so that it doesn't have a prototype, and so doesn't have the pre-existing inherited properties like toString
and valueOf
.
The inner loop, on the result of Object.keys
, is necessary because each object in the level2
array has a different name for its only property. That's an unusual and a bit awkward structure.
In ES2015 (aka "ES6") with Map
, it's very similar you just use new Map
and set
:
var map = new Map();
data.level1.level2.forEach(function(entry) {
Object.keys(entry).forEach(function(key) {
map.set(key, entry);
});
});
Live example:
var data = {
"level1": {
"level2": [{
"product1": [
"item1",
"item2"
]
}, {
"product2": [
"item1",
"item2"
]
}, {
"product3": [
"item5",
"item6"
]
}]
}
};
var map = new Map();
data.level1.level2.forEach(function(entry) {
Object.keys(entry).forEach(function(key) {
map.set(key, entry);
});
});
var name = "product2";
console.log(map.get(name));