Javascript更改对象结构

时间:2015-11-05 20:51:34

标签: javascript angularjs object underscore.js

我的对象如下:

{34: true, 35: false}

如何将Object转换为与此Array完全相同:

[{id: 34, _destroy: '1'}, {id: 35, _destroy: '0'}]

谢谢你们!

2 个答案:

答案 0 :(得分:0)

尝试此功能:

function convertIt(obj) {
        var keys = Object.keys(obj);
        var convertedObjs = [];    
        keys.forEach(function(key){
              var destroy = obj[key] ? "1" : "0";
              convertedObjs.push({"id": key, "_destroy" : destroy  });
        });
        return convertedObjs;
    }

答案 1 :(得分:0)

你们对此有何看法?

var myObject = {34: true, 35: false}
var result = [];
underscore.each(myObject, function(v, k) {
  result.push({id: k, _destroy: v ? '1' : '0'})
});

console.log(result);
> [{id: 34, _destroy: '1'}, {id: 35, _destroy: '0'}]