如何从JSON数组转换为JSON对象

时间:2014-04-09 16:45:59

标签: javascript json

我有这个JSON,我从网络服务电话回来了:

{
    "name": "My Name",
    "path": "my path",
    "id": "44",
    "type": "my type",
    "classes": "my classes"
},
{
    "name": "his Name",
    "path": "his path",
    "id": "76",
    "type": "his type",
    "classes": "his classes"
}

然后我需要将其转换为此格式

{
    "44" : { "name" : "My Name", "path" : "my path" },
    "76" : { "name" : "his Name", "path" : "his path" }
}

我最初的天真尝试是:

var myData = [];
for (var i = 0; i < rawData.length; i++) {
myData.push({
    rawData[i].id :
    {
        "path": rawData[i].path,
        "name": rawData[i].name
    }
});

因语法错误而失败,所以我最终得到了这个:

var myData = [];
for (var i = 0; i < rawData.length; i++) {
myData.push(rawData[i].id,
{
    "path": rawData[i].path,
    "name": rawData[i].name
});

它主要起作用。我的数组已填充,但问题是我的myData数组没有&#34; 44&#34;和&#34; 76&#34;对象的一部分,只是{ "name" : "", "path" : "" }部分。我希望这是因为我对JSON和javscript对象的工作方式缺乏了解。

4 个答案:

答案 0 :(得分:1)

不要使用Array.prototype.push(),使用方括号表示法并将输出定义为对象而不是数组。

var myData = {};
for (var i = 0; i < rawData.length; i++) {
    myData[rawData[i].id] = {
        "path": rawData[i].path,    
        "name": rawData[i].name
    }
}

答案 1 :(得分:1)

您想要的输出不是数组,所以这是您的起点。您所说的输出是对象,而不是数组。

您可以通过创建空白对象然后使用id作为关键字将对象添加到其中来构建结果:

var myData = {};
rawData.forEach(function(entry) {
    myData[entry.id] = {
        name: entry.name,
        path: entry.path
    };
});

或者,如果您不想使用forEach(它是ES5,但可以为旧版浏览器填充),则采用传统方式:

var myData = {};
var index, entry;
for (index = 0; index < rawData.length; ++index) {
    entry = rawData[index];
    myData[entry.id] = {
        name: entry.name,
        path: entry.path
    };
}

答案 2 :(得分:0)

您需要将您的ID转换为字符串吗?

var myData = {};
for (var i = 0; i < rawData.length; i++) {
    myData[String(rawData[i].id)] = {
        "path": rawData[i].path,
        "name": rawData[i].name
    };
}

答案 3 :(得分:0)

其他海报所写内容的变体:

// Create a new empty object.
var out = {};

// Loop over your array of objects
// Add the each object id as a key to the output object, and the object as the value.
for (var i = 0, l = arr.length; i <l; i++) {
  var obj = arr[i];
  out[obj.id] = obj;

  // Delete the properties from the newly added object you don't want.
  delete obj.id;
  delete obj.type;
  delete obj.classes;
}