Get element of JS object with an index

后端 未结 7 1236
南方客
南方客 2021-01-30 20:43

Ok so let\'s say that I have my object

myobj = {\"A\":[\"Abe\"], \"B\":[\"Bob\"]}

and I want to get the first element out of it. As in I want i

7条回答
  •  青春惊慌失措
    2021-01-30 21:17

    If you want a specific order, then you must use an array, not an object. Objects do not have a defined order.

    For example, using an array, you could do this:

    var myobj = [{"A":["B"]}, {"B": ["C"]}];
    var firstItem = myobj[0];
    

    Then, you can use myobj[0] to get the first object in the array.

    Or, depending upon what you're trying to do:

    var myobj = [{key: "A", val:["B"]}, {key: "B",  val:["C"]}];
    var firstKey = myobj[0].key;   // "A"
    var firstValue = myobj[0].val; // "["B"]
    

提交回复
热议问题