简体   繁体   English

遍历对象并将键和值推入数组

[英]Loop through an object and push key and value into an array

I've been trying to pass in an object with some data inside, I then want to push the results in that object into an array, but still keep the key and value names. 我一直试图传递一个带有一些数据的对象,然后我想将该对象中的结果推入数组,但仍保留键名和值名。

The data passed in: 数据传入:

App.config({
    dependencies: : {
        'html5shiv' : 'http://html5shiv.googlecode.com/svn/trunk/html5.js',
        'respondjs' : 'http://respondjs.googlecode.com/svn/trunk/respond.js'
    }
});

My array and logic (indicated where I'm stuck!): 我的数组和逻辑(指示卡住了!):

var deps = [];
App.config = function (obj) {
    var dep = obj.dependencies;
    for (var key in dep) {
        if (dep.hasOwnProperty(key)) {
            deps.push( /* stuck here */ );
        }
    }
    console.log(deps);
};

What I want 'deps' to end up with is: 我希望“ deps”最终得到的是:

[{
    'html5shiv': 'http://html5shiv.googlecode.com/svn/trunk/html5.js'
},{
    'respondjs': 'http://respondjs.googlecode.com/svn/trunk/respond.js'
}];

Can anyone advise on the best way to achieve this? 谁能建议实现这一目标的最佳方法?

Try this 尝试这个

for (var key in dep) {
        if (dep.hasOwnProperty(key)) {
            deps.push( dep[key].html5shiv);
            deps.push( dep[key].respondjs);
        }
    }

Updates: 更新:

for (var key in dep) {
     if (dep.hasOwnProperty(key)) {
          deps.push({key: dep[key]}); //Dynamic
      }
 }

尝试这个:

deps.push(dep[key]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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