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 tojBar
. - Looping through the
json
array using an old-fashioned index loop (notfor..in
, that's not what it's for). - Using an object literal (
{...}
) to create the entries to put injBar
. - Adding them to
jBar
by assignment to the next available slot. You could usejBar.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
精彩评论