简体   繁体   English

如何输入状态数组并求和对象的道具?

[英]How to enter state array and sum objects' props?

That is the code: I have order array in state, table which map it ,and now i need to summarize prices which are inside objects in array. 那就是代码:我在状态中有订单数组,映射它的表,现在我需要总结数组中对象内部的价格。 It should be counted in "handleCount" function,without adding any extra state objects, and return true cost of orders. 应该在“ handleCount”函数中计数,而不添加任何额外的状态对象,并返回真实的订单成本。 Then "newPrice"-(which store cost)should be passed to "handleSubmit function. 然后应将“ newPrice”-(存储成本)传递给“ handleSubmit”函数。

 const menuItems = [ { id: 1, name: "Pizza", price: 40 }, { id: 2, name: "Burger", price: 30 }, {id:3 , name: "Taco", price:15}, {id:4,name:"Cola",price:5} ]; class App extends React.Component { constructor() { super(); this.state = { order: [] }; } render() { return ( <div> <label> What would u like to order: <select price={this.state.price} name="list" onChange={this.addFood}> {menuItems.map((item) => (<option value={item.id}>{item.name}</option>))} </select> </label> <h1></h1> <h1></h1> <output>{this.state.counter}</output> <h1></h1> <button onClick={this.handleCount}>count</button> <button onClick={this.handleSubmit}>submit</button> <table size="sm" name="table"> <thead> <tr> <th>number</th> <th>name</th> <th>price</th> <th>delete?</th> </tr> </thead> <tbody> {this.state.order.map((item, index) => ( <tr> <th ordersId={item.id}>{index}</th> <th name={item.name}>{item.name}</th> <th price={item.price}>{item.price}</th> <button onClick={this.handleChangeDelete({ index })} name="deleteButton" id={"delete"+index}>-</button> </tr>) )} </tbody> </table> </div> ); } handleCount =(e)=>{ let newPrice = this.state.order.map(price); order.reduce((x, y) => x + y) console.log(newPrice); return (newPrice); } addFood =(e)=>{ //var integer = parseInt(this.state.price, 10); let newItem = menuItems.find((item) => item.id == e.target.value); this.setState({ order: [...this.state.order, newItem] }); console.log('state', this.state.order[0]); } handleChangeDelete =({ index }) => { //console.log(index); return (evt) => { let order = this.state.order; order.splice(index , 1); this.setState({ order: order }); }; }; handleChangeSelect =(e)=> { this.setState({value: event.target.price}); } handleSubmit =(event)=> { if(this.state.counter===0){ alert('You did not order anything'); }else{ alert('Your order is ready, it costs ' ); event.preventDefault(); }} } ReactDOM.render(<App />, document.getElementById("app")); 

 const menuItems = [ { id: 1, name: "Pizza", price: 40 }, { id: 2, name: "Burger", price: 30 }, { id: 3, name: "Taco", price: 15 }, { id: 4, name: "Cola", price: 5 } ]; console.log( sumByKey(menuItems) ); console.log( sumByKey(menuItems, "id") ); console.log( sumByKey(menuItems, "name") ); function sumByKey(arr, key){ key = key || "price"; // (*1) let join = isNaN( arr[0][key] ) ? ", " : 0; // (*2) return arr.reduce(function(prev, elem){ prev[key] = prev[key] + join + elem[key]; return prev; })[key]; // (*3) } 

(*1): It will sum the "price" values by default, if key is undefined. (* 1):如果key未定义,默认情况下它将对“价格”值求和。

(*2): Checking the first element's key value. (* 2):检查第一个元素的key If it's not NaN - later we will place 0 between the sum of elements. 如果不是NaN-稍后我们将在元素总数之间放置0。 And if it's NaN (String) - commas. 如果是NaN(String)-逗号。

(*3): .reduce function will reduce the array up to one last element. (* 3) .reduce reduce函数将数组减少到最后一个元素。 And the function will show it's key value. 该函数将显示它的key

The simplest solution is: 最简单的解决方案是:

const menuItems = [
  { id: 1, name: "Pizza",  price: 40 },
  { id: 2, name: "Burger", price: 30 },
  { id: 3, name: "Taco",   price: 15 },
  { id: 4, name: "Cola",   price: 5  }
];

const pricesSum = menuItems => {
  return menuItems.reduce((prev, current) => {
             prev.price = prev.price + current.price;
             return prev;
           }
        ).price;
 }

const sum = pricesSum(menuItems);

More simple: 更简单:

const pricesSum = menuItems => {
  let sum = 0;
  menuItems.forEach(item => 
    sum += item.price
);

  return sum;
}

const sum = pricesSum(menuItems);

90 90

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM