开发者

another javascript copy question

开发者 https://www.devze.com 2023-03-21 09:06 出处:网络
The original json var json = [{ \"LABEL\":\"foo1\", \"DATA\":340020, \"BAR\":235 }, { \"LABEL\":\"foo2\", \"DATA\":140084, \"BAR\":330 },

The original json

var json = 
  [{ "LABEL":"foo1", "DATA":340020, "BAR":235 },
   { "LABEL":"foo2", "DATA":140084, "BAR":330 },
   { "LABEL":"fooN", "DATA":126489, "BAR":120 }];

Below the desired format, where new DATA correspon开发者_JAVA技巧ds to old BAR

  [{ "LABEL":"foo1", "DATA":235 },
   { "LABEL":"foo2", "DATA":330 },
   { "LABEL":"fooN", "DATA":120 }];


Nothing particularly fancy. I'd use a nested loop:

var index, jBar, obj;

jBar = [];
for (index = 0; index < json.length; ++index) {
    obj = json[index];
    jBar[index] = {LABEL: obj.LABEL, DATA: obj.BAR};
}

Key points of the above:

  • Using [] to create a new, blank array to assign to jBar.
  • Looping through the json array using an old-fashioned index loop (not for..in, that's not what it's for).
  • Using an object literal ({...}) to create the entries to put in jBar.
  • Adding them to jBar by assignment to the next available slot. You could use jBar.push({...}); instead, but surprisingly, it's slower on several platforms and this is perfectly clear, so...


var i;
    var json = 
  [{ "LABEL":"foo1", "DATA":340020, "BAR":235 },
   { "LABEL":"foo2", "DATA":140084, "BAR":330 },
   { "LABEL":"fooN", "DATA":126489, "BAR":120 }];

   var jBar =
  [{ "LABEL":"foo1", "DATA":235 },
   { "LABEL":"foo2", "DATA":330 },
   { "LABEL":"fooN", "DATA":120 }];

   for(var i=0;i<json.length;i++)
    jBar[i].DATA=json[i].DATA;

and now jbar have the same DATA as the json


you are setting Array property to undefined value. JSON.stringify ignores additional properties of arrays

0

精彩评论

暂无评论...
验证码 换一张
取 消