1

I have a array in this format

const Adicionais = [{
  ID: 0,
  Nome: 'Adiocinais Açai',
  MaxOpcoes: 3,
  Itens: [{
    Nome: 'Morango',
    Valor: 5.00,
    ID: 0,
  }, {
    Nome: 'Raspas de Chocolate',
    Valor: 5.00,
    ID: 1,
  }, {
    Nome: 'Biz de Chocolate',
    Valor: 5.00,
    ID: 2,
  }]
}]

I need to get the value of index VALOR inside the array ITENS and SUM the value of all items that I have an ID saved in another array of the items selected. I tried do this that form

const ValorAdicionas = ProdutoAdicionais.filter((item) =>  (item.Itens.filter((a) => (adicionaisChecked.includes(a.ID))).reduce((a, v) => a = a + v.Valor, 0)))

but does not work. The array ProdutosAdicionais have the value of array Adicionais, and the array adicionaisChecked have the ID of array Itens

3
  • 1
    whats the expected output? Commented Aug 27, 2021 at 16:22
  • the expected output is the sum of all indice VALOR of the element ID is inside that array AdicionaisChecked, example i have the ID of Item Banana and Melon, i need the sum of the indice VALOR of these items Commented Aug 27, 2021 at 16:30
  • 1
    There is no word "indice" in English. The closest I could think of is the plural of index, indices. But now I'm not sure if maybe you mean "property" or "key"... Please do update your question if either makes more sense. Commented Aug 27, 2021 at 16:54

2 Answers 2

1

const adicionaisChecked=[1];
const ProdutoAdicionais = [{
  ID: 0,
  Nome: 'Adiocinais Açai',
  MaxOpcoes: 3,
  Itens: [{
    Nome: 'Morango',
    Valor: 5.00,
    ID: 0,
  }, {
    Nome: 'Raspas de Chocolate',
    Valor: 5.00,
    ID: 1,
  }, {
    Nome: 'Biz de Chocolate',
    Valor: 5.00,
    ID: 2,
  }]
}]


const valorAdicionas = ProdutoAdicionais.reduce((acc,item)=>{
 return acc.concat(item.Itens.filter(a=>adicionaisChecked.includes(a.ID)))
},[]).reduce((a,v)=>a+v.Valor,0);

console.log(valorAdicionas);

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

Comments

1

I hope this code helping you

const Adicionais = [{
  ID: 0,
  Nome: 'Adiocinais Açai',
  MaxOpcoes: 3,
  Itens: [{
    Nome: 'Morango',
    Valor: 5.00,
    ID: 0,
  }, {
    Nome: 'Raspas de Chocolate',
    Valor: 5.00,
    ID: 1,
  }, {
    Nome: 'Biz de Chocolate',
    Valor: 5.00,
    ID: 2,
  }]
}]
adicionaisChecked = [0,1]
Adicionais.map(o=>o.Itens.filter(v=>adicionaisChecked.indexOf(v.ID) != -1)).map(k=>k.reduce((sum, prev)=>sum + prev.Valor,0))

Comments

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.