0

JSON:(this.schedulerForm.get("schedularList").value => this array has contains below array.. )

    const result = [{
                     formula_id:1,
                     quantity1:10,
                     quantity2:20,
                     quantity3:40
                     }]

conversion JSON:(Above JSON array contains 1 object with 3 quantity value. I need to seperate quantity value in each object with same formula_id along with month and year.. output should be like shown below.)

    const result = [{
                      formula_id:1,
                      year:this.year,
                      month: this.month,
                      quantity:10
                      },
                       {
                      formula_id:1,
                      year:this.year,
                      month: this.month,
                      quantity:20
                      },
                      {
                      formula_id:1,
                      year:this.year,
                      month: this.month,
                      quantity:40
                      }]

component.ts:

 month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];
  year = new Date().getFullYear();
  getDate(n){
    const date = new Date();
     return date.getMonth() + n;
  }
 save() {
    console.log(this.schedulerForm.get("schedularList").value)
 }

2
  • What have you tried so far? Commented Mar 18, 2020 at 14:40
  • This is still irrelative to Angular and Reactive Forms! Commented Mar 18, 2020 at 15:36

1 Answer 1

1

I think something like this will help you:

const data = [{
  formula_id:1,
  quantity1:10,
  quantity2:20,
  quantity3:40
}];

const year = new Date().getFullYear();
const month = 13;

const mapItem = obj => propQuantity => ({
  formula_id: obj.formula_id,
  year, 
  month,
  quantity: obj[propQuantity]
});

const props = ["quantity1", "quantity2", "quantity3"];

const result = data.reduce((agg, obj) => [...agg, ...props.map(mapItem(obj))], []);
console.log(result);

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for this solution.. How to do vice versa of this solution??
Could you please tell how to do vice versa??? i have tried using groupby function but not getting proper data..
You are asking to reconstruct the original array?
@Rekha sorry for the delay, i prepared a jsfiddle with the code that you asking for: jsfiddle.net/kevynsax/en21m4zu/13 please let me know if this attend your needs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.