-1

Let me know if you can take the first key and the first value set by an object as you can do with an array.

var a = [1,2];
var b = {1: "first", 2: "second"};

a[0] //1
b[0] //undefined

What would be the fastest way to get only first object key-val

{1: "first"}

EDIT

I need to have like result an object result = {1: "first"};

Thanks

Gus
  • 863
  • 2
  • 13
  • 27

4 Answers4

2

var b = {1: "first", 2: "second"};

for (first in b) break;

console.log("Key : " + first);
console.log("Value : " + b[first]);
Weedoze
  • 12,306
  • 1
  • 32
  • 52
  • 1
    The iteration order with `for...in` is not guaranteed, so depending on the object and the browser, you may get different results. – VLAZ Nov 09 '16 at 11:58
1

Use Object.keys for that and additionally Array#sort method can be used if necessary.

var b = {
  1: "first",
  2: "second"
};

console.log(
  b[Object.keys(b).sort(function(a, b) {
    return a - b;
  })[0]]
)
Pranav C Balan
  • 106,305
  • 21
  • 136
  • 157
1

First of all, there is no such thing like first key in Javascript objects. It's simply because their keys are unordered. If you actually want to get the smallest numeric key in an object, you can just directly get the value via its key like b[1]. If the smallest key is not given beforehand, you will need to use Object.keys for retrieving the key list, then get the smallest key from that list with Math.min.

var smallestKey = Math.min(...Object.keys(b));
var result = {[smallestKey]: b[smallestKey]};
Lewis
  • 11,912
  • 9
  • 59
  • 79
  • If you wonder what those three dots are in the code above, check this [post](http://stackoverflow.com/q/31048953/1372621) – Stacked Nov 09 '16 at 16:16
-1

Just another suggestion using the filter method:

const b = {1: "first", 2: "second"};
const firstKeyValue = Object.keys(b).filter( (a) => {
    return a
})

console.log(e.splice(0, 1))
Jackthomson
  • 626
  • 7
  • 22
  • What does that filter accomplish? At most, it's filtering out falsey values but that's it. It can literally be replaced with `.filter(Boolean)` and you'd get the same result back. – VLAZ Nov 09 '16 at 13:03