0

I am looping through my array to get the corresponding field value:

var someFun = function (nm) {
    var names = [{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}];

    for (var i=0; i < names.length; i++) {
        if (names[i].name === nm) return names[i].age;
    }
};

var username = 'tom';
var printme = someFun(username);
console.log('hey: ', printme)

How can I do the same using Object.keys(), or map, or forEach? Much cleaner and ES6 compliant.

3
  • 1
    names is an array. You would not use Object.keys! Commented Nov 15, 2017 at 13:46
  • return {joe: 'nine', tom: 'ten'}[nm]; would do the job :-) Commented Nov 15, 2017 at 13:48
  • for(var key in names[i]){ console.log("key: " + key + ", value: " + names[i][key]); } Commented Nov 15, 2017 at 13:51

5 Answers 5

3

Simply use find

([{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}].find( (s)=> s.name=="tom" )||{}).age //10

([{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}].find( (s)=> s.name=="tom2" )||{}).age //undefined

Demo

var names = [{
  name: 'joe',
  age: 'nine'
}, {
  name: 'tom',
  age: 'ten'
}];

function getAge(names, name) {
  return (names.find((s) => s.name == name) || {}).age;
}

console.log(getAge(names, "tom"))
console.log(getAge(names, "tom2"))

Sign up to request clarification or add additional context in comments.

2 Comments

This throws an exception when it doesn't find Tom.
@Bergi fixed it
1

You can use array.prototype.find:

var names = [{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}];
var someFun = (nm) => {        
    var found = names.find(el => el.name === nm);
    return found && found.age || null; 
}
console.log(someFun('tom'));

Comments

1

From Array.prototype.find()

The find() method returns the value of the first element in the array that satisfies the provided testing function.

If there are multiples objects with the same name?

With Array.prototype.filter()

var names = [{
    name: 'joe',
    age: 9
  },
  {
    name: 'tom',
    age: 10
  },
  {
    name: 'frank',
    age: 9
  },
  {
    name: 'joe',
    age: 15
  }
];

function getData(arr, search) {
  // Filter array of objects by a search pair
  return arr.filter(o => o[search[0]] === search[1]);
}

function listBy(arr, k) {
  // Output values from an array of objects by a key as a comma separated string 
  return arr.map(o => o[k]).join(",");
}

console.log(getData(names, ["name", "joe"]));
console.log(listBy(getData(names, ["name", "tom"]), "age"));
console.log(listBy(getData(names, ["age", 9]), "name"));

Comments

0

IE doesn't support find, check the Browser compatibility. Maybe you don't need to support IE, but it's still a gets 3.74% of global usage as of Oct 2017. However, it does support filter.

DEMO

var users = [
  { name: "Bill", age: 'nine' },
  { name: 'Tedd', age: 'ten' }
];

function getAgeFromUsers(name) {
  const arr = users.filter(u => u.name === name);
  return !!arr.length ? arr[0].age : "That user ain't here";
}

console.log(getAgeFromUsers('Tedd'));
console.log(getAgeFromUsers("Lion 'O"));

Comments

-1
var someFun = nm => {
    const names = [{name: 'joe', age: 'nine'}, {name: 'tom', age: 'ten'}];
    const foundName = names.find(name => name.name === nm)

    return foundName ? foundName.age : null
};

This replicates what you have above. Although i would personally return the object then age the age from that instead of just returning the age.

4 Comments

This throws an exception when it doesn't find Tom.
Good spot, amended.
Thanks. The variable should be named boy, not foundName though
Assuming all the names will be boy names, that would work. I think playing off the original variables name makes a bit more sense though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.