Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change json structure to look like another json structure

I want to change my json structure, how can I do it?

im getting a json that looks like this:

 body: {
     "111111": {
         "name": "exp1",
         "status": 10000
     },
     "222222": {
         "name": "exp2",
         "status": 20000
     },
     "333333": {
         "name": "exp3",
         "status": 30000
     }
 }

but I need it in this structure:

 body: {
     bulks: [{
         "id": "111111",
         "name": "exp1",
         "status": 100000
     }, {
         "id": "222222",
         "name": "exp2",
         "status": 200000
     }, {
         "id": "333333",
         "name": "exp3",
         "status": 300000
     }]
 }

Cause in my html I want to read it like this:

<div *ngIf="showingList">
  <div class="list-bg"  *ngFor="#bulk of listBulks | async">
    ID: {{bulk.id}} name of item: {{bulk.name}}
  </div>
</div>
like image 684
jack miao Avatar asked Mar 12 '23 15:03

jack miao


2 Answers

Using Object#entries and Array#map with spread operator.

const data={body:{111111:{name:"exp1",status:1e4},222222:{name:"exp2",status:2e4},333333:{name:"exp3",status:3e4}}};


const res = {body:{bulk:Object
.entries(data.body)
.map(a=>({id: a[0], ...a[1]}))}};

console.log(res);
like image 62
kemicofa ghost Avatar answered Mar 25 '23 11:03

kemicofa ghost


You can do it using reduce:

var body = {
    "111111": {
        "name": "exp1",
        "status": 10000
    },
    "222222": {
        "name": "exp2",
        "status": 20000
    },
    "333333": {
        "name": "exp3",
        "status": 30000
    }
}

var bodyArray = Object.keys(body).reduce(function(result, key) {
    var item = body[key];
    item.id = key;
    result.push(item)
    return result;
}, []);
like image 45
Arun Ghosh Avatar answered Mar 25 '23 12:03

Arun Ghosh