如何在循环中创建对象文字数组?
我需要创建一个像这样的对象文字数组:
var myColumnDefs = [
{key:"label", sortable:true, resizeable:true},
{key:"notes", sortable:true,resizeable:true},......
在这样的循环中:
for (var i = 0; i < oFullResponse.results.length; i++) {
console.log(oFullResponse.results[i].label);
}
数组的每个元素中 key
的值应该是 results[i].label
。
I need to create an array of object literals like this:
var myColumnDefs = [
{key:"label", sortable:true, resizeable:true},
{key:"notes", sortable:true,resizeable:true},......
In a loop like this:
for (var i = 0; i < oFullResponse.results.length; i++) {
console.log(oFullResponse.results[i].label);
}
The value of key
should be results[i].label
in each element of the array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
RaYell 的回答很好——它回答了你的问题。
在我看来,您确实应该创建一个由标签作为键的对象,并将子对象作为值:
上述方法应该比在整个对象数组中搜索每次访问的键要快得多且符合习惯。
RaYell's answer is good - it answers your question.
It seems to me though that you should really be creating an object keyed by labels with sub-objects as values:
The above approach should be much faster and idiomatic than searching the entire object array for a key for each access.
你可以在 ES6 中做类似的事情。
You can do something like that in ES6.
这就是 Array#map 的内容擅长
This is what Array#map are good at
如果您想使用 ES6 比 @tetra 更进一步,您可以使用 对象传播语法 并执行如下操作:
If you want to go even further than @tetra with ES6 you can use the Object spread syntax and do something like this:
这会起作用:
This will work:
与 Nick Riggs 的想法相同,但我创建了一个构造函数,并使用它在数组中推送一个新对象。它避免了类的键的重复:
In the same idea of Nick Riggs but I create a constructor, and a push a new object in the array by using it. It avoid the repetition of the keys of the class:
我将创建数组,然后将对象文字附加到其中。
I'd create the array and then append the object literals to it.