简体   繁体   English

将对象转换为angular2 Typescript中的数组

[英]converting an object into arrays in angular2 Typescript

I have an object which is getting dynamically loaded from REST response. 我有一个从REST响应动态加载的对象。 Now i have to convert this object into 2 arrays. 现在我必须将此对象转换为2个数组。 1) an array with key and values in which the value is null. 1)具有键和值的数组,其中值为null。 2) an array with key and values in which the value is not null. 2)具有键和值的数组,其中值不为空。

And these both arrays, i need to display them in html with key and values in sorted order like. 而这两个数组,我需要在html中显示它们,键和值按排序顺序显示。 first the not null values and then later the null values. 首先是非空值,然后是空值。

object1 : {
'name' : 'xyz',
'age' : '23',
'dob' : null,
'address' : null
}

Am finding a problem while converting this object into an array! 在将此对象转换为数组时发现问题! What i have been trying is 我一直在尝试的是

this.notNullValues = new Array<string>();
for(let obj of this.object1){
console.log(obj);
}

You can have a look at the below code. 您可以查看以下代码。 Also you can do the same with Object.keys instead of for..in . 您也可以使用Object.keys而不是for..in执行相同的操作。

Also, you can check like this, if(object1[key] == null) 另外,你可以像这样检查, if(object1[key] == null)

 var object1 = { 'name' : 'xyz', 'age' : '23', 'dob' : null, 'address' : null }; var nullArray = []; var notNullArray = []; for(let key in object1){ var item = {}; item[key] = object1[key]; if(object1[key]){ notNullArray.push(item); } else { nullArray.push(item); } } console.log(nullArray); console.log(notNullArray); 

With Object.keys , 使用Object.keys

 var object1 = { 'name' : 'xyz', 'age' : '23', 'dob' : null, 'address' : null }; var nullArray = []; var notNullArray = []; Object.keys(object1).forEach(function(key) { var item = {}; item[key] = object1[key]; if(object1[key]){ notNullArray.push(item); } else { nullArray.push(item); } }); console.log(nullArray); console.log(notNullArray); 

    var notNullValues = new Array();
    var nullValues = new Array();
    for(let key in object1){
    var value = object1[key];
    if(value ===null){
      nullValues.push({
        key: value;
      });
    } else {
      notNullValues.push({
          key: value;
      });
    }
});

Hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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