0

我是 JavaScript 新手。我相信这对有经验的人来说很容易。

Amazon AWS SDK for Node.JS 的 SimpleDB getAttributes 函数返回如下数据数组:

my_JSON_object = {"Attributes":[{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"}]}

我想将它转换成这样的简单对象:

my_JSON_object = {"Attributes":{"myName":"myValue","myName":"myValue",...}}

这样我就可以使用点语法来访问事物,例如:Attributes.myName 等。

我该如何进行这样的转换?

4

3 回答 3

2
var my_JSON_object = {"Attributes":[{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"},{"Name":"myName","Value":"myValue"}]}

var my_new_JSON_object = { 'Attributes' : {} };

my_JSON_object.Attributes.forEach( function ( value, index ) {
    my_new_JSON_object.Attributes[ value.Name ] = value.Value;
} );
于 2013-08-16T21:05:03.050 回答
0
var json = {"Attributes":[
    {"Name":"myName","Value":"myValue"},
    {"Name":"myName","Value":"myValue"},
    {"Name":"myName","Value":"myValue"},
    {"Name":"myName","Value":"myValue"},
    {"Name":"myName","Value":"myValue"},
    {"Name":"myName","Value":"myValue"},
    {"Name":"myName","Value":"myValue"},
    {"Name":"myName","Value":"myValue"},
    {"Name":"myName","Value":"myValue"}
]}

var attrs = json.Attributes.slice(0);

json.Attributes = {};

for(var i = 0, len = attrs.length; i < len; i++) {
    var attr = json.Attributes[i],
        key = attr.Name,
        val = attr.Value;

    json.Attributes[key] = val;
}
于 2013-08-16T21:02:35.867 回答
0

UnderscoreJS是做这些事情的优秀库。它将使您的代码更清晰,更易于维护。

var result = _.chain(my_JSON_object.Attributes)
.map(function(item){return [item.Name, item.Value]})
.object().value();

如果您是该语言的新手,这可能会有点让人不知所措,但相信我,从长远来看,它会很有帮助。

于 2013-08-16T22:01:54.823 回答