【问题标题】:How to flat json in Angular? (1 lvl down) [duplicate]如何在Angular中扁平化json? (1 lvl down)[重复]
【发布时间】:2018-08-03 11:45:16
【问题描述】:

我有这种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"
},

谁能帮我转换一下?

【问题讨论】:

  • 您可以发布您的试验以提供帮助吗?
  • 这是一个对象数组吗?请放置适当的结构

标签: javascript json


【解决方案1】:

我使用新的 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);

【讨论】:

  • 谢谢你,你是天才!! :D
【解决方案2】:

我创建了一个 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];
        }
      }
  }


}

希望能帮到你!

【讨论】:

  • 我真的非常感谢你,但我使用了上面的解决方案。无论如何,谢谢。
【解决方案3】:
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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 2012-07-01
    • 2021-05-24
    • 2011-11-15
    • 2021-11-19
    相关资源
    最近更新 更多