1

I tried to create a function and pass the parameter that is for him to search and return the list, however, he looks for "parameter" instead of "cardapio"

function I want to call:

gerenateList(cardapio);
gerenateList(payments);

function that I created

export function generateList(parameter){
    let menu = dataJson.parameter.map((i) => {
        return `*${i.id}* - ${i.name}\n`;
        
    });
return menu;

dataJson.json

{
 "cardapio":[
        {
            "id":1,
            "name":"X-Burguer",
            "type":"Burguer",
            "price":"9.99"
        }, {
            "id":2,
            "name":"X-Salada",
            "type":"Burguer",
            "price":"9.99"
        }, {
            "id":3,
            "name":"X-Tudo",
            "type":"Burguer",
            "price":"9.99"
        }],
"payments":[
        {
            "id":1,
            "name":"Dinheiro",
            "type":"Money"
        }, {
            "id":2,
            "name":"Cartão de débito",
            "type":"Debit"
        }, {
            "id":3,
            "name":"Cartão de crédito - Visa",
            "type":"Visa"
        }]
}

desired exit result

//cardapio
*1* - X-Burguer
*2* - X-Salada
*3* - X-Tudo

//payments
*1* - Dinheiro
*2* - Cartão de débito
*3* - Cartão de crédito - Visa
Vivek Jain
  • 2,730
  • 6
  • 12
  • 27
KillerDogs
  • 31
  • 1
  • 1
  • 3

1 Answers1

1

Your main issue is in this line:

dataJson.parameter

Change it with:

dataJson[parameter]

var dataJson = {
    "cardapio": [
        {
            "id": 1,
            "name": "X-Burguer",
            "type": "Burguer",
            "price": "9.99"
        }, {
            "id": 2,
            "name": "X-Salada",
            "type": "Burguer",
            "price": "9.99"
        }, {
            "id": 3,
            "name": "X-Tudo",
            "type": "Burguer",
            "price": "9.99"
        }],
    "payments": [
        {
            "id": 1,
            "name": "Dinheiro",
            "type": "Money"
        }, {
            "id": 2,
            "name": "Cartão de débito",
            "type": "Debit"
        }, {
            "id": 3,
            "name": "Cartão de crédito - Visa",
            "type": "Visa"
        }]
};

function gerenateList(parameter) {
    let menu = dataJson[parameter].map(function (i) {
        return `*${i.id}* - ${i.name}\n`;
    });
    return menu;
}

var result = gerenateList('cardapio');

console.log(result);
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
  • you could also add some validation in case the Object does not have the given key `Object.keys(dataJson).map(key => { if(key == parameter) {...}})` or `if(Object.keys(dataJson).find(key => key == parameter) !== undefined)` – Jairo Nava Magaña Sep 17 '20 at 15:25
  • it worked well man, thank you very much – KillerDogs Sep 18 '20 at 11:40