使用Javascript将对象(元素)向上移动一步

时间:2012-06-29 09:02:06

标签: javascript object filter javascript-objects extjs4.1

我有几个这样的对象:

enter image description here

我想将typevalue向上移动一步,以便它们位于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;
};

但它不起作用。

4 个答案:

答案 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);

结果:

enter image description here

查看完整的演示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