只要对象属性不是NaN,就将对象推入数组 [英] Push objects to array so long as object property is not NaN

查看:50
本文介绍了只要对象属性不是NaN,就将对象推入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用.filter来实现此目的,但是我不确定如何实现。

I am aware that I could use .filter to achieve this, however I am not sure how to implement it.

我在数组中具有以下对象

I have objects as follows within an array

item {
  title : g.attributes.title,
  category : g.attributes.categoryid,
  possible: g.attributes.possible
}

但是,

我需要确保仅将可能属性不是NaN的项推入数组。 >

这是我完整代码的摘录:

Here is an excerpt of my complete code:

function load(id){
   itemPath = lev1.lev2.lev3;
   items = [];
   for (var i = 0; i<itemPath.length; i++) {
      if(itemPath[i].attributes.id==id) {
         return itemPath[i].attributes.grades.models.map(function(g) {
            items.push(
               {
                  title : g.attributes.title,
                  category : g.attributes.categoryid,
                  possible: g.attributes.possible
               });
         });
      }
   }
}


推荐答案

function load(id){
   itemPath = lev1.lev2.lev3;
   items = [];
   for (var i = 0; i<itemPath.length; i++) {
      if(itemPath[i].attributes.id==id) {
         return itemPath[i].attributes.grades.models.map(function(g) {
            if(g.attributes.possible !== g.attributes.possible){
               return;
            }


            items.push(
               {
                  title : g.attributes.title,
                  category : g.attributes.categoryid,
                  possible: g.attributes.possible
               });
         });
      }
   }
}

NaN是唯一的财产本身不相等的javascript。只需遍历这些属性并检查它们是否可用,或者按照其他地方的建议在循环内使用内置的NaN()函数。

NaN is the only property in javascript that does not equal itself. Just loop over the properties and check them for this, or use the built in NaN() function within the loop as suggested elsewhere.

由于您仅担心可能的属性,因此只需使用 === self或isNaN来检查是否作为if语句的一部分()

Since you're only worried about the possible property, just check that one as part of the if statement using === self, or isNaN()

这篇关于只要对象属性不是NaN,就将对象推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆