我有一个对象数组,如下所示:
var data = [{country:"Austria", "customer name":"tech comp", order:"123"},
{country:"China", "customer name":"hk", order:"1111"},
{country:"UK", "customer name":"dev tech", order:"22"},
{country:"United State", "customer name":"technology", order:null} ];我想遍历每个属性,检查最长的字符串并返回字符数。
例如:在属性country上,United State是Austria, China and Uk中最长的字符串,所以我们返回它的长度为12。对于其他属性customer name和order也是如此。
问题是当属性具有null值时。我收到错误Cannot read property 'length' of null"
我尝试添加x => x[key].length || 0,所以如果不是0,那么它应该计算长度,但不起作用。
另外,在map中,我添加了一个if块if (x[key] != null) { x => x[key].length } else { x => 0 ; },但不起作用。
有任何建议,请如何添加条件,例如,如果值为空,则默认长度为0,这样我的代码才能正常工作?非常感谢。
var data = [
{country:"Austria", "customer name":"tech comp", order:"123"},
{country:"China", "customer name":"hk", order:"1111"},
{country:"UK", "customer name":"dev tech", order:"22"},
{country:"United State", "customer name":"technology", order:null} ];
const longestValue = (key, array) => Math.max(...array.map(x => x[key].length));
$.each(data[0], function(key){
console.log(key);
console.log(longestValue(key, data));
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
发布于 2021-02-08 01:17:29
您可以尝试在此处强制地图查询的真实值:
...array.map(x => x[key] && x[key].length)这应该首先检查xkey是否为true/是否有长度,如果不是,则返回false。这应该可以防止抛出错误。
经典的if ( xkey ) {...},如果xkey的值不正确,则返回该函数也可以,但在map中有点难看。
https://stackoverflow.com/questions/66090676
复制相似问题