Aamir Shaikh Aamir Shaikh - 1 month ago 7
jQuery Question

Create new Array if the Object Key is encountered and push the Value into it

I have the following objects...

var object1 = {
TransactionType: 'Service PO',
Level1: 'Payment Terms',
Level2: ''
};
var object2 = {
TransactionType: '',
Level1: '',
Level2: 'PT1'
};
var object3 = {
TransactionType: '',
Level1: '',
Level2: 'PT2'
};
var object4 = {
TransactionType: '',
Level1: 'Delivery Terms',
Level2: ''
};
var object5 = {
TransactionType: '',
Level1: '',
Level2: 'DT1'
};
var object6 = {
TransactionType: '',
Level1: '',
Level2: 'DT2'
};
var object7 = {
TransactionType: 'Material PO',
Level1: 'Transportation Terms',
Level2: ''
};


Now the real scenario is,


  1. First check the TransactionType, if it contains any value like in our case it has 'Service PO', then create an array and start pushing the objects into that array (in our case it will go till object6).

  2. But as object7 contains TransactionType, it wont insert into the array instead create a new array and repeat the same process.

  3. so basically the 1st array will contain 6 objects and the second array will contain only 1 object.

    Note, there could be 'n' number of objects, so the only thing to keep in mind is 'TransactionType'. As soon as you encounter that the next 'TransactionType' contains any value, stop pushing the objects into the array.
    How to achieve this using jQuery or Javascript. any help would be highly appreciated..
    Thanks


Answer
   Finally i solved it as per my requirement.whenever the 'TransactionType' is encountered, i Just kept on saving the data in object key which is 'TermsCategories'.
   [FIDDLE][1]
  [1]: https://jsfiddle.net/hwuzbbz8/

Note the above solution was according to my requirement. you can customize it accordingly whenever such situation arises in your project. Sorry for the identation. thanks