-3
var data =[
    {
        name:"xyz",
        meals:[
         {num:3.5},{num:4 },{num:6.5},{num:3}
            ],
        deposits:[
            {date:"", amount:3000},
            {date:"", amount:2400},
            {date:"", amount:300},
        ];
    },
    {
        name:"abc",
        meals:[
         {num:3.5},{num:4 },{num:6.5},{num:3}
            ],
        deposits:[
            {date:"", amount:3000},
            {date:"", amount:2400},
            {date:"", amount:300},
        ];
    }
];

I want to get the sum of meals & deposits for every name or object.

7
  • Sorry, for any kind of error because i am a newbie Commented Jul 19, 2018 at 16:11
  • 1
    Please post actual data instead of images Commented Jul 19, 2018 at 16:11
  • @PrantaSaha what is expected output? Commented Jul 19, 2018 at 16:15
  • just use properly reduce function, after reading the documentation Commented Jul 19, 2018 at 16:16
  • @amrender singh, I want to get total number of meals and amount of deposits for each person. Commented Jul 19, 2018 at 16:18

1 Answer 1

0

Use Array.map and Array.reduce

var data =[{name:"xyz",meals:[{num:3.5},{num:4 },{num:6.5},{num:3}],deposits:[{date:"", amount:3000},{date:"", amount:2400},{date:"", amount:300}]},{name:"abc",meals:[{num:3.5},{num:4 },{num:6.5},{num:3}],deposits:[{date:"", amount:3000},{date:"", amount:2400},{date:"", amount:300}]}];
    
let result = data.map(({name, meals, deposits}) => ({name, meals : meals.reduce((a,c) => a + c.num, 0), deposits : deposits.reduce((a,c) => a + c.amount, 0)}));
console.log(result);

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

1 Comment

@PrantaSaha - Glad to help you :)

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.