Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
function getFields(list, field, otherwise) {
    //  determine once whether or not to use the 'otherwise'
    var alt = typeof otherwise !== 'undefined';
    //  reduce the provided list to an array only containing the requested field
    return list.reduce(function(carry, item) {
        //  If item is an object and contains the field, add its value and the value of 'otherwise' if it was provided
        if (typeof item === 'object' && field in item) {
            carry.push(item[field]);
        }
        else if (alt) {
            carry.push(otherwise);
        }
        //  return the 'carry' (which is the list of matched field values)
        return carry;
    }, []);
}
var myArray = [{foo: 1, bar: 2}, {bar: 3, baz: 4}, {foo: 5, baz: 6}];
//. no 'otherwise' (meaning it'll be undefined)
console.log(getFields(myArray, 'foo'));
//. otherwise=3
console.log(getFields(myArray, 'foo', 3));
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers