0

これが私が持っているものです...

整形式の JSON 配列

[
    {"id":"1","networkType":1,"controllerIp":"10.255.135.22","redirectType":0,"networkCost":1351,"networkWeight":64888,"notes":"This is a network for network 1","name":"n1"},
    {"id":"4","networkType":1,"controllerIp":"10.255.150.24","redirectType":0,"networkCost":1344,"networkWeight":745,"notes":"This is a network for network 4","name":"n4"},
    {"id":"3","networkType":2,"controllerIp":"10.255.150.22","redirectType":0,"networkCost":13,"networkWeight":6888,"notes":"This is a network for network 3","name":"n3"},
    {"id":"2","networkType":3,"controllerIp":"10.255.654.22","redirectType":0,"networkCost":13,"networkWeight":6888,"notes":"This is a network for network 2","name":"n2"}
]

ここで、この配列の各部分に 2 つの新しい要素を追加したいと思います...

私は使用しています:

    function addPrefix(rawJSON){

        var orgStr = rawJSON;

            //Loop through all the groups of .... networks, sites, resources, components
            $.each(myData1,function(key,val){
                /*
                    key would be key1,key2,key3
                    innerjson would be the name and value **
                */

                //Alerts and logging of the variable. VAL is the entire group {...}
                console.log(val); //should show you the value   
                //Now append the following to the groups...
                //"data" : val.name,
                //"metadata" : {"id" : val.id},


                alert(val.name); //Should say n1,n2,n3...nn
            });

            return orgStr;

    }

したがって、新しい配列は次のようになります。

[
    {"data" : "1", "metadata" : {"id" : "n1"}, "id":"1","networkType":1,"controllerIp":"10.255.135.22","redirectType":0,"networkCost":1351,"networkWeight":64888,"notes":"This is a network for network 1","name":"n1"},
    {"data" : "4", "metadata" : {"id" : "n4"}, "id":"4","networkType":1,"controllerIp":"10.255.150.24","redirectType":0,"networkCost":1344,"networkWeight":745,"notes":"This is a network for network 4","name":"n4"},
    {"data" : "2", "metadata" : {"id" : "n2"}, "id":"3","networkType":2,"controllerIp":"10.255.150.22","redirectType":0,"networkCost":13,"networkWeight":6888,"notes":"This is a network for network 3","name":"n3"},
    {"data" : "3", "metadata" : {"id" : "n3"}, "id":"2","networkType":3,"controllerIp":"10.255.654.22","redirectType":0,"networkCost":13,"networkWeight":6888,"notes":"This is a network for network 2","name":"n2"}
]

それはどのように行われますか?またはそれを行うことさえできますか?

4

2 に答える 2

0

配列構造を変更する最も簡単な方法は、 - を使用することmapです。一部のブラウザーはまだこの機能をサポートしていないため、アンダースコアを好みます。

これは簡単に行うことができます:

data = _(data).map(function(value, index) { 
  value.push(some_more_data);
  return value; 
});
于 2013-11-05T13:21:45.090 に答える