search

Home  >  Q&A  >  body text

javascript - js 数据格式问题

var name = {
a:'haha'
b:'xixi'
c:'hehe'

}
怎样转换成如下格式:就是把除了c的全拿进other中
var name = {
other:{
a:'haha'
b:'xixi'
}
c:'hehe'
}

求大神指教

天蓬老师天蓬老师2902 days ago290

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-04-10 15:09:25

    需求奇奇怪怪的…

    function selectName(obj, name) {
        var res = {other:{}};
        for(var n in obj) {
            if(n != name) res.other[n] = obj[n];
            else res[n] = obj[n];
        }
        return res;
    }
    function exceptName(obj) {
        var res = {other:{}},
            names = [].slice.call(arguments, 1);
        for(var n in obj) {
            if(names.indexOf(n)!=-1) res.other[n] = obj[n];
            else res[n] = obj[n];
        }
        return res;
    }
    selectName({a:'haha', b:'xixi', c:'hehe'}, 'c');
    exceptName({a:'haha', b:'xixi', c:'hehe'}, 'a', 'b');
    

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-10 15:09:25

    有别于公子的答案,因为你的需求里面只有一个要保留的,所以此方法只循环一次,所以效率应该会快一些(其中portectKey可以作为参数传入,也可以写死)

    function clearObj(obj){
        var protectKeys = ['c'],
            obj = JSON.parse(JSON.stringify(obj)), //根据公子的建议,这里增加这一行
            pNum = protectKeys.length,
            newObj={},
            protectKey;
        for(var i=0;i<pNum;i++){
            protectKey = protectKeys[i];
            newObj[protectKey]=obj[protectKey];
            delete obj[protectKey];
        }
        newObj.other = obj;
        return newObj;
    }
    var newObj = clearObj({a:'haha',b:'xixi',c:'hehe'});
    

    如果是只有ab要放入other里,也差不多啦。

    function clearObj(obj){
        var protectKeys = ['a','b'],
            obj = JSON.parse(JSON.stringify(obj)), //根据公子的建议,这里增加这一行
            pNum = protectKeys.length,
            protectKey;
        obj.other = {};
        for(var i=0;i<pNum;i++){
            protectKey = protectKeys[i];
            obj.other[protectKey]=obj[protectKey];
            delete obj[protectKey];
        }
        return obj;
    }
    var newObj = clearObj({a:'haha',b:'xixi',c:'hehe'});
    

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 15:09:25

    如果你使用underscore的话,很简单:

    var others = _.omit(name, 'c');
    name = {
      others: others,
      c: name.c
    }
    

    reply
    0
  • Cancelreply