我有以下JSON对象。
"Department": [
{
"depType": "Testing",
"name": "xyz",
"address":""
},
{
"deptype": "Developer",
"name": "abc"
}
]
我想根据deptartment(depType)的类型创建另一个对象。像这样的东西
"Testing":{
"name": "xyz",
"address":""
},
"Developer":{
"name": "abc"
}
在Object.keys的帮助下,我能够获得密钥
答案 0 :(得分:1)
"depType"
有一些属性命名问题。解决了这个问题。JSON.parse(JSON.stringify(orgObj))
"Department"
for(var i=0; i<dep.length; i++)
。arrObj.hasOwnProperty( "depType" )
newObj[arrObj.depType] = arrObj;
"depType"
摆脱它的旧delete
属性。
<强> jsBin demo 强>
var myjson = {
"Department": [
{
"depType": "Testing", // NOTE: "camelCase"
"name": "xyz",
"address":""
},
{
"depType": "Developer", // FIX: "camelCase" !!
"name": "abc"
}
]
};
function depTypify( orgObj ) {
var objCopy = JSON.parse(JSON.stringify(orgObj)); // Fresh copy
var newObj = {};
for(var prop in objCopy){
if(prop === "Department") {
var dep = objCopy[prop]; // get Department Array
for(var i=0; i<dep.length; i++) { // Loop array
var arrObj = dep[i]; // Explore Each Array Object
if(arrObj.hasOwnProperty( "depType" )) {
newObj[arrObj.depType] = arrObj;
delete arrObj.depType; // We don't need it any more
}
}
}
}
return newObj;
}
var myNewJson = depTypify( myjson );
如果你这样做,console.log( myNewJson )
这就是你得到的:
[object Object] {
Developer: [object Object] {
name: "abc"
},
Testing: [object Object] {
address: "",
name: "xyz"
}
}
好消息是你的旧json仍然完好无损。