如何将数组转换为对象?

时间:2016-12-08 10:08:48

标签: javascript arrays

我有一个不同的数组对象

{
  prac:[{
         "name":"xxx",
         "id":"1"
        }],
  abc: [{
        "description":"this is test description",
         "status":"active"
       }]
  }

在这里,我想将 prac 数组转换为对象。

2 个答案:

答案 0 :(得分:2)

您应该获取数组的第一个元素。而已

var obj = {
  prac: [{
    "name": "xxx",
    "id": "1"
  }],
  abc: [{
    "description": "this is test description",
    "status": "active"
  }]
};

obj.prac = obj.prac[0];

console.log(obj);

答案 1 :(得分:0)

试试这个:



var jsonObj = {
  prac:[{
         "name":"xxx",
         "id":"1"
        }],
  abc: [{
        "description":"this is test description",
         "status":"active"
       }]
  };
  
var arrObj = jsonObj.prac;  

function toObject(arr) {
  var newJson = {};
  for (var i = 0; i < arr.length; ++i)
    newJson[i] = arr[i];
  return newJson;
}

console.log(toObject(arrObj));
&#13;
&#13;
&#13;