简体   繁体   中英

one to many object relationship

hi i have one array of objects trying to make a chat-bot using discord so one input give me more than output under certain circumstances but i'm struggling , here is my array

let message = [{
        "message": "hi",
        "reply": "1-order 2-inquiry 3-complain"
    },

    {
        "message": "1",
        "reply": "please clarify your address"
    },

    {
        "message": "2",
        "reply": "about 1-delivery time 2-delivery fees",
        "response": {
            "1": "from 8 am to 11 pm",
            "2": "10$"
        }
    },

    {
        "message": "3",
        "reply": "1-expired products 2-other",
        "response": {
            "1": "please clarify the product name ",
            "2": "please leave a comment"
        }
    }
]

the question here how can i specify that when i enter 1 the chat-bot will respond with that specific reply that means one input has many outputs so how can i make this

many thanks.

You can use Array.find which returns the first item in an array that matches with our condition. We can implement it like this

const input = '1'; // we assume the input was '1'

const output = message.find(q => {
    return (q.message === input);
});

console.log(output.reply);

Here, try it

 let message = [ { "message": "hi", "reply": "1-order 2-inquiry 3-complain" }, { "message": "1", "reply": "please clarify your address" }, { "message": "2", "reply": "about 1-delivery time 2-delivery fees", "response": { "1": "from 8 am to 11 pm", "2": "10$" } }, { "message": "3", "reply": "1-expired products 2-other", "response": { "1": "please clarify the product name ", "2": "please leave a comment" } } ]; const input = '1'; // we assume the input was '1' const output = message.find(q => { return (q.message === input); }); console.log(output.reply);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM