Home > OS >  I have an array of objects, but I only want to access a single quality of a single object. (in javas
I have an array of objects, but I only want to access a single quality of a single object. (in javas

Time:01-10

I have the following array of objects, It contains the name of the employee, and his salary. I must create a function that receives that array, the name of the employee, and returns the salary of the employee, multiplied by 12.

This is the object: var emeployees = [{ name: 'Manuel', salary: 1000, }, { name: 'Flor', salary: 4000, }, { name: 'Maria', salary: 500, } ]; this is the function function anualSalary(employees, name) { // I dont know how to do this

}

anualSalary(empleados, 'Flor'); => 48000 anualSalary(empleados, 'Manuel;); => 12000

CodePudding user response:

function annualSalary(name) {
    var employee = employees.find((employee) => employee.name === name);
    return employee.salary * 12;
}

CodePudding user response:

basic JSON manipulation / reading in JavaScript is very easy as you can just address the object keys with jsonObject.keyName. I just use a for loop and iterate over all JSON object in your object array. In your case the code could look something like this:

var emeployees = [{ name: 'Manuel', salary: 1000, }, { name: 'Flor', salary: 4000, }, { name: 'Maria', salary: 500, }];

function anualSalary(employees, name) {
    for (const employee of employees){
        if (employee.name = name){
            return employee.salary * 12;
        }
    }
}

console.log(anualSalary(emeployees, "Flor"));

EDIT:

  • Updated snippet to make function signature fit given example
  •  Tags:  
  • Related