如何在Angular中扁平化json? (降低1级)

时间:2018-08-03 11:45:16

标签: javascript json

我有这种json(长度200):

{

  id: 5, 
  date: "2018-05-05"

   tmp: {
       warranty: "no";
       discount: "yes"
    }

},
 .... (and more)

我要创建:

{
  id: 5, 
  date: "2018-05-05"
  warranty: "no";
  discount: "yes"
},

有人可以帮我转换吗?

3 个答案:

答案 0 :(得分:0)

我创建一个StackBlizt示例来做到这一点:

https://stackblitz.com/edit/angular-hezrsa

看看flatJson()方法。

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public obj = {};
  private startObj= {
  id: 5, 
  date: "2018-05-05",
  tmp: {
       warranty: "no",
       discount: "yes"
    }

  };


  constructor(){
    this.flatJson();
  }

  flatJson():void{
     for (var prop in this.startObj) {
        console.log(prop);
        if(typeof this.startObj[prop] == 'object'){
              for (var nestedprop in this.startObj[prop]) {
                 this.obj[nestedprop] = this.startObj[prop][nestedprop];
          }
        } else{
           this.obj[prop] = this.startObj[prop];
        }
      }
  }


}

希望我能帮助您!

答案 1 :(得分:0)

使用新的ES6语法的方式。

  1. 首先使用对象分解,提取零件。
  2. 然后使用您的重组对象布局图。

例如

const a = [{
  id: 5, 
  date: "2018-05-05",
  tmp: {
    warranty: "no",
    discount: "yes"
  }
}];


const ret = a.map(v => {
  const {id, date, tmp: {warranty, discount}} = v;
  return {id, date, warranty, discount};
});

console.log(ret);

答案 2 :(得分:0)

var obj ={
    id: 5, 
  date: "2018-05-05",
   tmp: {
       warranty: "no",
       discount: "yes",
       obj2: {
       nestedone: 'yes'
        }
    }
}

var newObj = new Object();
    addtoArr(obj);
 function addtoArr(obj){
    for(o in obj){
  console.log("key" +o +"value" + obj[o]) ;
        if(typeof obj[o] !='object'){
    newObj[o] = obj[o];
    console.log(newObj);
  }
   else {
    return addtoArr(obj[o]);
}
}
};
console.log(newObj);

This will work everytime even if your nested json is much more nested than what you mentioned above.