Eric Fortis
Eric Fortis

Reputation: 17360

another javascript copy question

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 corresponds to old BAR

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

Upvotes: 0

Views: 87

Answers (3)

Andrey Sidorov
Andrey Sidorov

Reputation: 25466

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

Upvotes: 0

TreantBG
TreantBG

Reputation: 1222

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

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075755

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...

Upvotes: 3

Related Questions