I separated them to two var items first one contained the first array second the second array. Once done I used the first array to loop 4 times based on bstype. and then used the $.root.secondarray to loop through the second item. Thanks everyone.
Knockoutjs about foreach child parent
Question
I have a model that contains 2 arrays of type and name address and so on as follows:
var model = [{"bstype":1},{"bstype":2},{"bstype":3},{"bstype":4}],
[{"bstype":1, "name":"John","Address":"Sample address"},
[{"bstype":1, "name":"John","Address":"Sample address"},
[{"bstype":3, "name":"John","Address":"Sample address"},
{"bstype":2 ,"name":"John","Address":"Sample address"}];
[{"bstype":2, "name":"John","Address":"Sample address"},
[{"bstype":4, "name":"John","Address":"Sample address"}];
What i want it to do is to create a list of:
something like
I am not sure about this part how to implement it that is why it was gibberish.
bstype":1 will have a view of following
[{"bstype":1, "name":"John","Address":"Sample address"},
[{"bstype":1, "name":"John","Address":"Sample address"},
bstype"2: will have a view of following
{"bstype":2 ,"name":"John","Address":"Sample address"}];
[{"bstype":2, "name":"John","Address":"Sample address"},
bstype":3 has only one
[{"bstype":3, "name":"John","Address":"Sample address"},
and so on so forth.
I am using knockout I have checked the site it only discusses about foreach but not how to access the child elements.
I hope this makes sense.
Thanks
Solution 2
OTHER TIPS
A helper method to combine two arrays as you've done by the same key:
var model = [{"bstype":1},{"bstype":2},{"bstype":3},{"bstype":4}];
var modelChildren = [{"bstype":1, "name":"John","Address":"Sample address"},
{"bstype":1, "name":"John","Address":"Sample address"},
{"bstype":3, "name":"John","Address":"Sample address"},
{"bstype":2 ,"name":"John","Address":"Sample address"},
{"bstype":2, "name":"John","Address":"Sample address"},
{"bstype":4, "name":"John","Address":"Sample address"}];
This method will give you a new array "grouped by" the matching bstype:
var result = model.map(function(elem)
{
return {
bstype: elem.bstype,
children: modelChildren.filter(function(childElem) {
return childElem.bstype == elem.bstype;
})
};
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow