问题描述:

I am getting a json response that looks like this :

{

"+143500000": {

"inbox": "active",

"Messages": [{

"id": "sms001",

"Sender": "Tom",

"Text": "hello world"

}, {

"id": "sms002",

"Sender": "Jones",

"Text": "bye world"

}]

}

}

I want to save this response to local storage but it needs to look like this

{

"+143500000": {

"inbox": "active",

"Messages": {

"sms001": {

"Sender": "Tom",

"Text": "hello world"

},

"sms002": {

"Sender": "Jones",

"Text": "bye world"

}}

}

}

How can i modify the response i get to make it look like that. I am a beginner at javascript. Your help would be greatly appreciated. Would love a sample in javascript or jquery to do this .

Thanks

网友答案:

The logic should be very easy to follow. Note that your starting json has Messages as an array, but you are requesting that it have named properties, so it must be turned into an object.

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

Live demo here (click).

网友答案:
// 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;
}
相关阅读:
Top