0

我有一个 JavaScript 数组对象,如下所示:

var Array = [{"foo1":"bar1","foo2":"bar2","foo3":"bar3","foo4":"bar4","foo5":"bar5","foo6":"bar6","foo7":"bar7"},
{"foo1":"bar5","foo2":"bar6","foo3":"bar7","foo4":"bar8","foo5":"bar9","foo6":"bar10","foo7":"bar10"}]

我希望将此数组转换为 JSON 格式的字符串以进行序列化,看起来像这样。我正在使用JSON.stringify序列化它应该给我如下的结果字符串:

'"fooAry" : [{"foo1":"bar1","foo2":"bar2","foo3":"bar3","foo4":"bar4"},
{"foo1":"bar5","foo2":"bar6","foo3":"bar7","foo4":"bar8"}]'

如您所见,这里有两件事:

  1. 去掉数组中键值对的最后 3 个元素
  2. 将密钥附加fooAry到生成的 JSON 字符串。
4

1 回答 1

1

假设您确实可以保证对象中的元素顺序:

var a = [
    {"foo1":"bar1","foo2":"bar2","foo3":"bar3","foo4":"bar4","foo5":"bar5","foo6":"bar6","foo7":"bar7"},
    {"foo1":"bar5","foo2":"bar6","foo3":"bar7","foo4":"bar8","foo5":"bar9","foo6":"bar10","foo7":"bar10"}
];

// Object.keys polyfill
if (!Object.keys) Object.keys = function(o){
    var ret=[], p;
    for (p in o){
        if (Object.prototype.hasOwnProperty.call(o, p)){
            ret.push(p);
        }
    }
    return ret;
}

function removeLast3(obj){   
    var ks = Object.keys(obj).slice(0, -3);
    var newobj = {}, k, i;
    for (i=0; k=ks[i]; i++){
        newobj[k] = obj[k];
    }
    return newobj;
}

var newA = [removeLast3(a[0]), removeLast3(a[1])];
var strA = '"fooAry": ' + JSON.stringify(newA);
于 2013-08-17T23:57:17.893 回答