【问题标题】:How to change json structure to look like another json structure如何将 json 结构更改为看起来像另一个 json 结构
【发布时间】:2016-11-28 18:17:42
【问题描述】:

我想改变我的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>

【问题讨论】:

  • 你试过什么?转换是一个简单的包装你确定你的数据正确吗? var listBulks = {body: {bulks: [oldBodyList]}};
  • @Sukima 我在哪里添加您建议的转换?我没有尝试任何东西,但我不知道该尝试什么......
  • 您将 JavaScript 放在哪里。 Angular 没有 JavaScript 吗?这是我能做的最好的。也许其他使用 Angular 的人知道的更多。

标签: javascript json html angular


【解决方案1】:

将 Object#entries 和 Array#map 与展开运算符一起使用。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这是一个很好的答案。只是一个指针,array.reduce 存在兼容性问题。请务必提及
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2020-11-17
      • 2019-08-27
      • 2016-01-22
      • 2017-03-21
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      相关资源
      最近更新 更多