Filter objects within a hashed array

Asked

Viewed 37 times

0

I am creating a program in JS plantation control and add() function, I want to add a filter to check if that hash (name) already exists, however, I am not getting:

let data = [];
let name = {};
data[name];

function menu(){
let option = Number(prompt('1- adicionar  2- apagar  3- exibir  0- sair'));
switch(option){
    case 1: add(); break;
    case 2: break;
    case 3: break;
    default: return 0;
}
}

function add(){
name = prompt('Nome:');
let day = prompt('Dia:');
let mouth = prompt('Mês:');
var exists = data.filter(function(obj){
    return 'name' in obj['name'] != name;
});
console.log(exists);
if (data[name]!=exists){
    alert(`${name} adicionado!`)
    data[name] = {name: name, date:{day:day, mouth:mouth}};
    menu();
}
else if(prompt(`${name} já existe! quer atualizar? S ou N`)!='S'){
    alert('voltando ao menu...');
    menu();
}
data[name] = {name: name, date:{day:day, mouth:mouth}};
}

menu();

1 answer

0


Some things in your code are not correct, such as:

  • The way you’re doing the filtering;
  • The verification (if) if the new item already exists;
  • The way you are adding to the array.

I changed these points in your code to work as you want. However, there is still room for improvements in your code.

let data = [];
let name = {};
data[name];

function menu(){
let option = Number(prompt('1- adicionar  2- apagar  3- exibir  0- sair'));
switch(option){
    case 1: add(); break;
    case 2: break;
    case 3: break;
    default: return 0;
}
}

function add(){
name = prompt('Nome:');
let day = prompt('Dia:');
let mouth = prompt('Mês:');
var exists = data.filter(function(obj){
    return obj['name'] === name;
}).length > 0;

if (!exists){
    alert(`${name} adicionado!`)
    data.push({name: name, date:{day:day, mouth:mouth}});
    menu();
}
else if(prompt(`${name} já existe! quer atualizar? S ou N`)!='S'){
    alert('voltando ao menu...');
    menu();
}
data[name] = {name: name, date:{day:day, mouth:mouth}};
}

menu();

  • thank you very much man, I’m just learning this content, I’ll give a scan in the code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.