I
I
Ivan2022-01-20 18:50:12
JavaScript
Ivan, 2022-01-20 18:50:12

How to find elements in an array and replace their values?

Hello! Faced with the most difficult task, which I have been solving for 6 hours. Help please...

So, we have a data.json file with the following content.

[{"input":"продаю машину","output":"ban"},{"input":"продаю коня","output":"moderation"},{"input":"продаю зебру","output":"normal"},{"input":"продаю льва","output":"normal"},{"input":"продаю льва","output":"normal"},{"input":"продаю осла"}]


You need to find exactly the occurrence of input and replace the output value in it, then return the full array with the replaced value and write it to a file. And that the case is not taken into account. And if duplicate inputs are found, you don’t need to write everything down, you need to leave only one. For example, you need to find the element where the input sells a lion , and replace the output ONLY for this element with moderation.

I did it, but it's kind of a crutch. Firstly, it eats a lot of resources, and secondly, it is somehow unprofessional. First we choose what to find, then we choose what to leave, then we collect the arrays into one.

How to make it easier?
let data = require('./data.json');
        let input = "input";
        let output = "output";
        let text = message.text.toLowerCase();
        let new_status = 'normal';  
          let data_find = data.filter(f => f.input.toLowerCase() === text);
            if (data_find.length !== 0) {
                let new_data = data.filter(function (f) {
                    return f.input.toLowerCase() !== text;
                });
                let data_replace = data_find.map(e => e[input].toLowerCase() === text ? ((e[output] = new_status), e) : e);
                // объединяем массивы и записываем
                new_data = new_data.concat(data_replace[0]);
                let filepatch = './detection/AutoBan/data.json';
                fs.outputJson(filepatch, new_data, err => {
                    if (err) return console.log(err);
                });
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
I Phoenix I, 2022-01-21
@PhoenixX33i

As an option...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question