虽然map
从对象列表中选择“列”是一种合适的解决方案,但它也有缺点。如果未明确检查列是否存在,则会抛出错误,并(最好)为您提供undefined
。我会选择一个reduce
解决方案,该解决方案可以忽略该属性,甚至可以将其设置为默认值。
function getFields(list, field) {
// reduce the provided list to an array only containing the requested field
return list.reduce(function(carry, item) {
// check if the item is actually an object and does contain the field
if (typeof item === 'object' && field in item) {
carry.push(item[field]);
}
// return the 'carry' (which is the list of matched field values)
return carry;
}, []);
}
jsbin示例
即使提供的列表中的项目之一不是对象或不包含该字段,这也将起作用。
如果项目不是对象或不包含该字段,则可以通过协商默认值来使其更加灵活。
function getFields(list, field, otherwise) {
// reduce the provided list to an array containing either the requested field or the alternative value
return list.reduce(function(carry, item) {
// If item is an object and contains the field, add its value and the value of otherwise if not
carry.push(typeof item === 'object' && field in item ? item[field] : otherwise);
// return the 'carry' (which is the list of matched field values)
return carry;
}, []);
}
jsbin示例
与map相同,因为返回数组的长度与提供的数组相同。(在这种情况下,a map
比a便宜一些reduce
):
function getFields(list, field, otherwise) {
// map the provided list to an array containing either the requested field or the alternative value
return list.map(function(item) {
// If item is an object and contains the field, add its value and the value of otherwise if not
return typeof item === 'object' && field in item ? item[field] : otherwise;
}, []);
}
jsbin示例
然后是最灵活的解决方案,您可以通过提供替代值来简单地在两种行为之间切换。
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;
}, []);
}
jsbin示例
正如上面的示例(希望如此)阐明了它的工作方式,让我们通过利用Array.concat
功能来稍微缩短功能。
function getFields(list, field, otherwise) {
var alt = typeof otherwise !== 'undefined';
return list.reduce(function(carry, item) {
return carry.concat(typeof item === 'object' && field in item ? item[field] : (alt ? otherwise : []));
}, []);
}
jsbin示例
var foos = objArray.pluck("foo");
。