我有几个这样的对象:
我想将type
和value
向上移动一步,以便它们位于field
旁边,然后删除data
。
当departments
转换为JSON时,它看起来像这样:
[
{"field" : "DEPARTMAN_NO",
"data" : { "type":"numeric" , "comparison":"eq" , "value":11 }
},
{"field" : "DEPARTMAN_ADI",
"data" : { "type":"string" , "value":"bir" }
}
]
我试过了:
departments = grid.filters.getFilterData();
i = {};
for(var i in department) {
department = i.data;
delete.department.data;
};
但它不起作用。
答案 0 :(得分:4)
1)首先,循环departments
,我们称之为department
的每个项目;
2)您希望将department.data
的属性移至department
,从另一个角度,您可以将department
的属性移至department.data
并返回department.data
,代码如:
var departments = [{
"field": "DEPARTMAN_NO",
"data": {
"type": "numeric",
"comparison": "eq",
"value": 11
}
}, {
"field": "DEPARTMAN_ADI",
"data": {
"type": "string",
"value": "bir"
}
}],
department;
for (var i = 0, len = departments.length; i < len; i++) {
department = departments[i]; // department
for (var key in department) {
if (key !== 'data' && department.data) {
department.data[key] = department[key];
}
}
departments[i] = department.data || department; // if no department.data, no change
}
console.log(departments);
结果:
查看完整的演示http://jsfiddle.net/KVYE5/
答案 1 :(得分:1)
department.type = department.data.type;
department.value = department.data.value;
delete department['data'];
答案 2 :(得分:1)
obj =
[
{"field" : "DEPARTMAN_NO",
"data" : { "type":"numeric" , "comparison":"eq" , "value":11 }
},
{"field" : "DEPARTMAN_ADI",
"data" : { "type":"string" , "value":"bir" }
}
];
for ( var item in obj ) {
if ( obj[item].field && obj[item].data ) { //check the 'field' and 'data' exist
obj[item].field = {
dept : obj[item].field , //department name is put into a property
type : obj[item].data.type, //so is data.type and data.value..
value: obj[item].data.value //..all are now contained in 'field'
};
delete obj[item].data; //remove the 'data' object
}
}
console.log(obj);
答案 3 :(得分:1)
我写了一个小的npm包,它可以满足您的要求:将属性移动到对象中的某个级别。
您可以在此处获取:https://www.npmjs.com/package/move-property-up-a-level
var movePropertyUpALevel = require('movePropertyUpALevel');
var fakeObj = {
poodle: {
first: {
hey: 'you'
},
second: 'meAgain'
}
};
movePropertyUpALevel(fakeObj, 'poodle');
console.log(fakeObj.first.hey);
//'you'
console.log(fakeObj.poodle);
//undefined