简体   繁体   中英

Javascript change Object structure

My object looks like this:

{34: true, 35: false}

How do I convert the Object to be exactly like this Array:

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

Thanks guys!

Try this function:

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;
    }

What do you guys think about this?

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'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM