Find Array Value in Object

0

I have the following object:

let Filmes = [{
                "Nome": "Harry Potter 1",
                "Preco": "50"
             },
             {
                "Nome": "Harry Potter 2",
                "Preco": "60"
             },
             {
                "Nome": "Harry Potter 3",
                "Preco": "70"
             }] 

let Cliente = ["Harry Potter 1", "Harry Potter 3"]
let ValorFinal = ""

How do I do this by using the Cliente array to check what Filmes and Cliente do you want? And after doing this, I get back the% w /% of the movie. The output of this would be:

  

Final value = 120

Because the Client wants Preco and Harry Potter 1 .

If possible in vanilla JS please

    
asked by anonymous 23.01.2018 / 13:15

2 answers

6

You can use filter and reduce .

let filmes = [{
                "Nome": "Harry Potter 1",
                "Preco": "50"
             },
             {
                "Nome": "Harry Potter 2",
                "Preco": "60"
             },
             {
                "Nome": "Harry Potter 3",
                "Preco": "70"
             }];

let cliente = ["Harry Potter 1", "Harry Potter 3"];

const escolhidos = filmes.filter((f) => cliente.includes(f.Nome));
const valor = escolhidos.reduce((a, b) => a + parseFloat(b.Preco), 0);

console.log(valor);
    
23.01.2018 / 13:26
1

I believe this iteration will bring the expected result:

var valorFinal = 0;

for (i = 0; i < Filmes.length; i++) {
    for (j = 0; j < Cliente.length; j++) {
        if (Cliente[j] == Filmes[i]["Nome"]) {
            valorFinal += Filmes[i]["Preco];
            break;
        }
    }
}
    
23.01.2018 / 13:23