-1

I have this kind of json (length 200):

{

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

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

},
 .... (and more)

I want to create:

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

Can anybody help me convert this?

Igor
  • 60,821
  • 10
  • 100
  • 175
dybleG
  • 51
  • 1
  • 10

3 Answers3

0

I create a StackBlizt example to how do this:

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

Look at flatJson() Method.

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];
        }
      }
  }


}

hope i help you!

0

The way I would do this using new ES6 syntax.

  1. First using object destructuring, extract the parts.
  2. Then map, with your restructured object layout.

eg.

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);
Keith
  • 22,005
  • 2
  • 27
  • 44
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.
Sreekar Sree
  • 404
  • 5
  • 14