如何删除对象中的键并用其值替换?

时间:2016-09-28 07:01:22

标签: javascript json

我有一个类似json的样本

var obj={
    "results":{
        "grade":"A",
        "marks":12
    },
    "data":{
        "name":"sam",
        "gender":"male",
        "age":10
    }
};

现在我想将json转换为:

var obj={
    "results":{
        "grade":"A",
        "marks":12
    },
    "name":"sam",
    "age":10
}

我正在使用每个循环

for(var exKey in obj) {
    if(exKey=='data'){
        //replace key data with its value
    }
}

但我无法弄清楚会做到这一点的逻辑。 所以有人可以帮助我,我怎样才能实现这一目标? 谢谢你的回复, 但如果我有一些复杂的json像:

var obj={
"results":{
    "grade":"A",
     "res":"fail",
    "marks":12
},
"data":{details:{"name":"sam",
                 "gender":"male",
                  "age":10
                }
 },
 "feespaid":"yes",
 "joindate":"sunday"

};

现在,如果我想修改或删除键值中的某些键,可以使用

var obj={
"results":{
    "grade":"A",
    "marks":12
},
"data":{details:{"name":"sam",
                  "age":10
                }
 },
 "joindate":"sunday"
 };

那么我们如何进入json并删除

3 个答案:

答案 0 :(得分:3)

使用inner for-in循环并使用bracket-notationvariable指定为key的{​​{1}}

object

修改:仅从var obj = { "results": { "grade": "A", "marks": 12 }, "data": { "name": "sam", "gender": "male", "age": 10 } }; for (var exKey in obj) { if (exKey == 'data') { for (var d in obj.data) { if (d != 'gender') obj[d] = obj.data[d]; } delete obj.data; } } console.log(obj);删除少数keys,使用Object关键字

delete

答案 1 :(得分:2)

一种不使用循环的方法:

obj.name = obj.data.name;
obj.age = obj.data.age;
delete obj.data;

使用for-in循环的另一种方式:

for(item in obj.data) obj[item] = obj.data[item]; // Add items from obj.data to obj
delete obj.gender;                                // Remove gender
delete obj.data;                                  // Remove obj.data

段:

var obj={
  "results":{
  "grade":"A",
  "marks":12
   },
  "data":{
   "name":"sam",
    "gender":"male",
   "age":10
  }
};

for(item in obj.data) obj[item] = obj.data[item];
delete obj.gender;
delete obj.data;

console.log(obj)

答案 2 :(得分:1)

for (var exKey in obj) {
    if(exKey=='data') {
        for (var dataKey in obj[exKey]) {
           obj[dataKey] = obj[exKey][dataKey];
        }
        delete obj[exKey];
    }
}

(我需要更多地调查解决方案) <击> 编辑:删除嵌套属性可以这样做:

var invalidProperties = ['gender', 'feespaid']; //add more if needed
function recursivelyDeleteProperties(obj) {
    for (var key in obj) {
        if(invalidProperties.indexOf(key) !== -1) {
            delete obj[key];
        } else {
            recursivelyDeleteProperties(obj[key]);
        }
    }
}

<击>