在保存到本地存储之前,如何修改我得到的 json 响应以使其看起来像这样

How can i modify the json response i get to make it look like this before saving to local storage

本文关键字:json 响应 像这样 看起来 修改 存储 保存 何修改      更新时间:2023-09-26

>我收到如下所示的 json 响应:

{
    "+143500000": {
        "inbox": "active",
            "Messages": [{
                "id": "sms001",
                "Sender": "Tom",
                "Text": "hello world"
        }, {
            "id": "sms002",
                "Sender": "Jones",
                "Text": "bye world"
        }]
    }
}

我想将此响应保存到本地存储,但它需要看起来像这样

{
    "+143500000": {
        "inbox": "active",
            "Messages": {
            "sms001": {
                "Sender": "Tom",
                "Text": "hello world"
        },
            "sms002": {
                "Sender": "Jones",
                "Text": "bye world"
        }}
    }
}

怎样才能修改我得到的响应,使其看起来像那样。我是javascript的初学者。您的帮助将不胜感激。希望有一个javascript或jquery中的样本来做到这一点。

谢谢

逻辑应该很容易理解。请注意,起始 json Messages为数组,但您请求它具有命名属性,因此必须将其转换为对象。

var data = {
  "+143500000": {
    "inbox": "active",
    "Messages": [
      {
        "id":"sms001",
        "Sender":"Tom",
        "Text": "hello world"
      },
      {
        "id":"sms002",
        "Sender":"Jones",
        "Text": "bye world"
      }
    ]
  }
};
var messages = {};
for (var i=0; i<data["+143500000"].Messages.length; ++i) {
  var item = data["+143500000"].Messages[i];
  messages[item.id] = item;
  delete messages[item.id].id;
}
data["+143500000"].Messages = messages;
console.log(data);
data = JSON.stringify(data);
console.log(data);
localStorage.myJson = data;
console.log(localStorage.myJson);
var retrievedData = localStorage.myJson;
console.log(retrievedData);

现场演示在这里(点击)。

// if your value is in `a`, then:
for (k in a)
  if (a.hasOwnProperty(k)) {
    hash = {};
    a[k].Messages.forEach(function(m) {
      hash[m.id] = m;
      delete m.id;
    });
  a[k].Messages = hash;
}