如何创建搜索和创建JSON列表的函数

时间:2020-09-17 14:56:41

标签: javascript json function

我试图创建一个函数并传递供他搜索并返回列表的参数,但是,他寻找的是“参数”而不是“ cardapio”

我要调用的功能:

gerenateList(cardapio);
gerenateList(payments);

我创建的功能

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"
        }]
}

所需的退出结果

//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

1 个答案:

答案 0 :(得分:1)

您的主要问题在这一行:

dataJson.parameter

使用以下方法进行更改:

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);