Vikram Saini
Vikram Saini

Reputation: 2769

how to loop inside repeating nested arrays in reactjs

I want to calculate the cost and i am stuck from past 1 hour.Here is my data

Todo: [{
    name: "primary",
    items: [{
        item: 'Todo itme #1',
        isDone: false,
        cost: 0
    }]
}, {
    name: "Secondary",
    items: [{
        item: 'Todo itme #1',
        isDone: false,
        cost: 0
    }]
}]

I want to loop on all items and compute the total cost.

but I am not able so solve it.

Entries inside items array can increase dynamically.

Please guide!

Upvotes: 0

Views: 133

Answers (3)

kind user
kind user

Reputation: 41913

Array#reduce solution.

let Todo = [{
  name: "primary",
  items: [{
    item: 'Todo itme #1',
    isDone: false,
    cost: 3
  }, {
    item: 'Todo itme #2',
    isDone: false,
    cost: 2
  }]
}, {
  name: "Secondary",
  items: [{
    item: 'Todo itme #3',
    isDone: false,
    cost: 1
  }]
}], 
   totalCost = Todo.reduce((s,a) => {
     return s + a.items.reduce((s,a) => s + a.cost, 0);
   }, 0);
  
  console.log(totalCost);

Upvotes: 3

Asmaa Almadhoun
Asmaa Almadhoun

Reputation: 299

this code will not cost time to use it and search for it, I use it always

componentDidMount() {
    let i=0;
    let cost = 0;
    let Todo = [
        {name:"primary",items:[{item:'Todo itme #1',isDone:false,cost:20}]},
        {name:"Secondary",items:[{item:'Todo itme #2',isDone:false,cost:5}]},
    ];
    Todo.map(function( itemElement ){
        let itemElement2 = itemElement.name;
        let item =itemElement.items;
        return [itemElement2, item];
    }).filter(function(value){
        if (typeof value[0] === 'string'){
            console.log( "name " +value[0]  )
        }
        if(typeof value[1] === "object") {
            console.log(
                "item in items : item " + i +" "+
                value[1][0].item + " "+
                value[1][0].isDone + " "+
                value[1][0].cost
            );
            cost+=parseInt(value[1][0].cost);
            console.log(' cost '+cost)
        }
        return value ;
    });

}

Upvotes: 0

Chris
Chris

Reputation: 59551

You just want to calculate the result of the sum? Then try this:

var sum = 0;
var Todo = [{
  name: "primary",
  items: [{
    item: 'Todo itme #1',
    isDone: false,
    cost: 35
  }]
}, {
  name: "Secondary",
  items: [{
    item: 'Todo itme #1',
    isDone: false,
    cost: 10
  }]
}];

Todo.forEach(function(todo) {
  todo.items.forEach(function(item) {
    sum += item.cost
  });
});

console.log(sum)

Upvotes: 2

Related Questions