如何将{" name":" myName"," value":" myValue"}对象的数组转换为&的对象#34; MYNAME":" myvalue的" JavaScript中的对?

时间:2013-08-16 20:54:30

标签: javascript node.js amazon-web-services key-value-coding

我是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等。

如何进行此类转化?

3 个答案:

答案 0 :(得分: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;
} );

答案 1 :(得分: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;
}

答案 2 :(得分:0)

UnderscoreJS是执行此类操作的绝佳库。它将使您的代码更清晰,更易于维护。

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

如果你是这门语言的新手,这可能有点压倒性,但从长远来看,相信我会有很大的帮助。