简体   繁体   中英

How to push non empty object into an array?

Input:

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

Expected output:

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

ie push only if an address is available.

My code:

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

But it is not working since I did a mistake, can anyone please help me? Thanks.

You can get the keys of the npi object, filter them to only get ones that are 'testN' (where N is any number) and that have an .address that is not blank, then map that:

 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) 

Further reading:

Try this:

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

You can do it using Object.keys()

 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) 

This code will solve your problem:

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

The issue is how you are accessing your properties in your object. You need to use bracket notation for accessing properties dynamically, like so.

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM