Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select nth item inside the object

Say if you were unable to access a certain item inside an object through dot notation like objectName.objectItem i.e. it has random name al the time. Is there a way to alternatively access it like second item?

how to get item2 from this object by only knowing that it is second item there?:

something: {
  item1: "text",
  item2: "text",
  item3: "text:,
  ...
}
like image 612
Ilja Avatar asked Mar 01 '16 11:03

Ilja


2 Answers

Order of keys are not fixed in javascript object.

You can try

var secondKey = Object.keys(something)[1]; //fetched the key at second index
alert(something[secondKey ]);
like image 81
gurvinder372 Avatar answered Sep 18 '22 11:09

gurvinder372


Object keys have no order, but you can define your own binary relation that orders the keys.

Say, you only consider keys starting with "item" and a numeral suffix such as item23, then you can per your own definition translate this into the number 23 and decide that item23 is the 23rd item in your array.

Mind that this is completely arbitrary and only true in so far you want it to be so in your code.

That said, you can implement a function that filters all keys (considering only those starting with "item"), parse the numeral suffix into a number and then compare that to what index of an item you want.

This code does exactly what I've supposed you want to do:

function nth(obj, n)
{
  var key, i;

  for (key in obj)
  {
    if (obj.hasOwnProperty(key)) // always do this when you scan an object
    {
      if (key.indexOf("item") === 0) // this is the filter
      {
        i = parseInt(key.substring(4), 10); // parse the numeral after "item"
        if (i === n)
        {
          return obj[key]; // return this value
        }
      }
    }
  }

  return null;
}
like image 40
pid Avatar answered Sep 18 '22 11:09

pid