如何将非空对象推入数组?

时间:2017-06-23 15:01:31

标签: javascript arrays angular object

输入:

var npi = {'test1':{'address':'','num':'12'},'test2':{'address':'','num':'12'},'test3':{'address':'cleveland','num':'12'},'test4':{'address':'hostun','num':'12'}}

预期输出:

var array = ['cleaveland','hostun']

即仅在地址可用时才推送。

我的代码:

for(var i = 0;i < = 4;i++){
    if(npi.test+''+i.address) {
        array.push(npi.test+''+i.address);
    }
}

但由于我犯了错误,它无法正常工作,有人可以帮助我吗?  感谢。

5 个答案:

答案 0 :(得分:2)

您可以获取npi对象的密钥,过滤它们以仅获取'testN'(其中N是任意数字)并且.address不为空的var npi = {'not':{},'nsi':{}, 'test1':{'address':'','num':'12'},'test2':{'address':'','num':'12'},'test3':{'address':'cleveland','num':'12'},'test4':{'address':'hostun','num':'12'}} var array = Object.keys(npi) .filter(function(k) { return /^test\d+$/.test(k) && npi[k].address }) .map(function(k) { return npi[k].address }) console.log(array) ,然后映射:

&#13;
&#13;
setTimeout(function() {
  console.log("First");
  console.log("Second");
}, 5000);
&#13;
&#13;
&#13;

进一步阅读:

答案 1 :(得分:0)

试试这个:

var objNPI = Json.parse(npi); for(var i = 0;i < = 4;i++){ var prop = 
objNPI[i].address; if(prop) { array.push(objNPI); } }

答案 2 :(得分:0)

您可以使用Object.keys()

执行此操作

&#13;
&#13;
var npi = {
    'test1': {
        'address': '',
        'num': '12'
    },
    'test2': {
        'address': '',
        'num': '12'
    },
    'test3': {
        'address': 'cleveland',
        'num': '12'
    },
    'test4': {
        'address': 'hostun',
        'num': '12'
    }
};

var addressArr = [];

var objKeys = Object.keys(npi);
for (var i = 0; i < objKeys.length; i++) {
    if (npi[objKeys[i]].address) {
        addressArr.push(npi[objKeys[i]].address);
    }
}

console.log(addressArr)
&#13;
&#13;
&#13;

答案 3 :(得分:0)

此代码将解决您的问题:

var array = [];
var keys = Object.keys(npi).slice();
for(key of keys){
  if(npi[key].address != ''){
    array.push(npi[key].address);
  }
}

答案 4 :(得分:0)

问题是您如何访问对象中的属性。您需要使用括号表示法动态访问属性,如此。

&#13;
&#13;
var npi = {'test1':{'address':'','num':'12'},'test2':{'address':'','num':'12'},'test3':{'address':'cleveland','num':'12'},'test4':{'address':'hostun','num':'12'}};

var array = []

for(var i = 1;i <= 4;i++){
  // access npi test properties dynamically with bracket [] syntax
  var address = npi["test"+i].address;
  if(address) {
    array.push(address);
  }
}

console.log(array);
&#13;
&#13;
&#13;