如何将json结构更改为类似于另一个json结构



我想更改json结构,该怎么做?

我得到一个json,看起来像这样:

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

但我需要这种结构:

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

因为在我的html中,我想这样读:

<div *ngIf="showingList">
  <div class="list-bg"  *ngFor="#bulk of listBulks | async">
    ID: {{bulk.id}} name of item: {{bulk.name}}
  </div>
</div>

使用带有排列运算符的Object#条目和Array#映射。

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);

您可以使用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;
}, []);

作为reduce的最简单替代方案,您可以使用map()函数。

const body = {
  "111111": {
    "name": "exp1",
    "status": 10000
  },
  "222222": {
    "name": "exp2",
    "status": 20000
  },
  "333333": {
    "name": "exp3",
    "status": 30000
  }
}
const newArray = Object.keys(body).map(function(key) {
  const newObject = {
    id: key,
    ...body[key]
  };
  return newObject;
});
console.log(newArray);

最新更新