输入:
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);
}
}
但由于我犯了错误,它无法正常工作,有人可以帮助我吗? 感谢。
答案 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)
,然后映射:
setTimeout(function() {
console.log("First");
console.log("Second");
}, 5000);
&#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()
执行此操作
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;
答案 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)
问题是您如何访问对象中的属性。您需要使用括号表示法动态访问属性,如此。
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;