Asked  7 Months ago    Answers:  5   Viewed   21 times

I would like to get the keys of a JavaScript object as an array, either in jQuery or pure JavaScript.

Is there a less verbose way than this?

var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
    keys.push(key);
}

 Answers

30

Use Object.keys:

var foo = {
  'alpha': 'puffin',
  'beta': 'beagle'
};

var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta'] 
// (or maybe some other order, keys are unordered).

This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.

The ES5-shim has a implementation of Object.keys you can steal

Tuesday, June 1, 2021
 
innovation
answered 7 Months ago
20

Actually I figured it out myself after playing around. So I realized that using cursor.getColumnIndex("name_of_column") will return the column's index to be used in commands like cursor.getInt(cursor.getColumnIndex("_id"));. All I have to do is just use a for loop to go through the whole list and use cursor.moveToNext() to just iterate through the rows collected. I came up with this minutes after I posted this question. :)

Friday, August 13, 2021
 
HuLu ViCa
answered 4 Months ago
24

What is the correct way to construct a Directive Prologue with multiple Directives?

As the spec you linked says,

a Directive Prologue is the longest sequence of ExpressionStatement productions occurring [at the begin of a script or function] and where each [of them] consists entirely of a StringLiteral.

So you can just string them together, every of these string-literal-statements is a Directive; and can have an implementation-specific meaning (only the Use-Strict-Directive is specified). Your hunch is correct, this should work:

"use bar"
"use strict"; 'use x';
'use foo';
Thursday, August 19, 2021
 
TaylorMac
answered 4 Months ago
37

Date does not take a timezone parameter in that way. My thought is that Chrome is just ignoring it.

new Date(year, month, day [, hour, minute, second, millisecond])

Please see @Brett's comment below for more information.

Tuesday, August 24, 2021
 
pije76
answered 4 Months ago
93

For an easier and more reusable code pass to the method the object and the index, as follows:

function getAllBefore(obj, index){
  var sum=0;
  for(var i=0; i<index; i++){
    sum+=obj[i].width;
  }

  return sum;
}

And call it like this:

getAllBefore(obj, 5);
Tuesday, August 31, 2021
 
LukeP
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share