Reputation: 315
Here some of my code:
var fashion = [];
/* LEVEL 1 CATEGORIES */
fashion.push({ level1 : 'Mens', inner:[] });
fashion.push({ level1 : 'Womens', inner:[] });
I am trying to then push a value into the inner
array, only for the Mens
category.
I can write:
/* LEVEL 2 CATEGORIES */
fashion[0].inner.push({ level2 : 'Shoes' });
fashion[0].inner.push({ level2 : 'Accessories'});
But i want to target it not by index 0, but by the "Mens" value. Is there a way of doing that? So it becomes something like:
fashion['Mens'].inner.push({ level2 : 'Shoes'});
but this syntax is wrong.
Upvotes: 0
Views: 138
Reputation: 144709
There is no jQuery object in your code. A jQuery object is an object that is returned by jQuery constructor ($()
). You have a simple JavaScript array of objects. For filtering the array element you can use the Array.prototype.filter
method:
fashion.filter(function(el) {
return el.level1 === 'Mens';
})[0].inner.push({ level2 : 'Shoes' });
filter
returns an array of matching elements. So you should either iterate through the returned array (using Array.prototype.forEach
method) or use the bracket notation for getting the target object by index. It should be noted that filter
will return an empty array where is no matching element, so it would better to check the length
property of the returned array before using bracket notation.
Upvotes: 1
Reputation: 137
Another simple solution is to change fashion and inner into objects:
var fashion = {};
/* LEVEL 1 CATEGORIES */
fashion.Mens.inner = {};
fashion.Womens.inner = {};
/* LEVEL 2 CATEGORIES */
fashion.Mens.inner.Shoes = [];
fashion.Mens.inner.Accessories = [];
Upvotes: 0
Reputation: 6031
using javascript for
loop.
var fashion = [];
fashion.push({ level1 : 'Mens', inner:[] });
fashion.push({ level1 : 'Womens', inner:[] });
console.log(fashion);
for(i=0;i<fashion.length;i++){
if(fashion[i].level1 == "Mens"){
fashion[i].inner.push({ level2 : 'Shoes' });
fashion[i].inner.push({ level2 : 'Accessories'});
}
}
console.log(fashion);
Check DEMO
Upvotes: 0
Reputation: 1078
you could use jquery each loop
$.each(fashion, function( index, value ) {
if(value.level1 === 'Mens') { // specify your condition
value.inner.push({ level2 : 'Shoes' });
// your code to push value
}
});
Upvotes: 0