-1
I need to sum up the values of several objects from within a list.
For this, I made a map go through my list and set that if the object has the true property it should do a reduce of all these objects and sum them up.
But at the end I come across:
TypeError: valores.reduce is not a function
How can I fix this?
import React, { Component, } from 'react'
import {Table } from 'react-bootstrap'
import {consultarExtrato} from '../../services/Extrato/index'
let saldo = window.localStorage.getItem('saldo');
class Teste extends Component {
constructor(props){
super(props);
this.state = {
//Array que recebe os Itens da API
transacoes: [],
}
}
componentDidMount(){
consultarExtrato().then(dados => this.setState({transacoes: dados}))
}
render() {
return (
<div>
{
//Tabela com os dados
}
<Table striped bordered hover variant="dark">
<tbody>
{
this.state.transacoes.map((item) => {
var valores = item.valor
if(item.credito){
function sum(acc, val){
return acc + val
}
let resposta = valores.reduce(sum)
return (
<td>{resposta}</td>
)
}
})
}
</tbody>
</Table>
</div>
)
}
}
export default Teste;
what you have inside transactions?
– novic
Inside transactions there is an array with several objects, this is the link to it: https://gitlab.com/desafio-conta-simples/developer/-/blob/master/mocks/transacoes.json
– user210629
In the novic case I want to add only those that are equal to true.
– user210629
valores.reduce(sum)
is not aarray
! and because of the error message, it is a key to each item, that is, it is not there that makes it?– novic
I’m researching a solution, not really there. Now I’m trying to map transactions, take object values, put these values inside a new array, reduce that array, and then use reduce within the reduced array. Does it work?
– user210629
I made this Novic change, entered the values inside an array and made the reduction and then the sum, but when I print my result in the console.log, I don’t get the sum, but the values of the previous array, without being added together.
– user210629
toquinho if you want to print the data and at the end show the sum?
– novic
I need to print the sum of the values of the objects that are true in the API. @novic
– user210629
I don’t need to print the data, just show the final sum value.
– user210629