虽然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 相同,因为返回数组的长度与提供的数组相同。(在这种情况下 amap
比 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 示例