How to select nth item inside the object

2020-03-02 05:08发布

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:,
  ...
}

2条回答
▲ chillily
2楼-- · 2020-03-02 05:29

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 ]);
查看更多
【Aperson】
3楼-- · 2020-03-02 05:47

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;
}
查看更多
登录 后发表回答