get index of Javascript object with Array

douglas_rogers2
Kilo Contributor

What should be the ideal solution for this

Input: var inc2 = {
  num
: 'INC111',
  sd
: 'email'
};
var inc2 = {
  num
: 'INC222',
  foo
: 'internet'
}

var arr = [];
arr.push(inc2,inc1);

Index of the inc1 object to be 1.

1 ACCEPTED SOLUTION

antin_s
ServiceNow Employee
ServiceNow Employee

From the title, i see you are looking for getting the index of an array in Javascript object( based on a value)? Please correct me if I am wrong.



If thats the case, you can use 'map' function. Also, I think the inc2 one line # 1 is typo, I corrected it.



var inc1 = {


  num: 'INC111',


  sd: 'email'


};


var inc2 = {


  num: 'INC222',


  foo: 'internet'


}




var arr = [];


arr.push(inc2,inc1);




pos = arr.map(function(input) { return input.num; }).indexOf('INC111');




gs.log(pos);



Hope this helps. Mark the answer as correct/helpful based on impact.



Thanks


Antin


View solution in original post

7 REPLIES 7

Patrick Fedigan
Giga Guru

Hello Douglas,



Arrays in most languages start at '0'. Pushing inc2 first would result in it's index being 0 and then pushing inc1 would result in it's index being 1.



If you are more interested in why arrays start at zero you can dive pretty deep here Why are zero-based arrays the norm? - Software Engineering Stack Exchange



Cheers,



Patrick


Chuck Tomasi
Tera Patron

Technically, it fails because you didn't declare "inc1". I'll assume the first inc2 should be inc1.



You are correct, the index of inc1 is one. Like Patrick said 'inc2' is going to be at position 0.



I copy/pasted your script in to Scripts - Background on my instance (changed the first inc2 to inc1) and added this at the end to verify.



gs.info(arr[1].num);



The response was "INC111"


antin_s
ServiceNow Employee
ServiceNow Employee

From the title, i see you are looking for getting the index of an array in Javascript object( based on a value)? Please correct me if I am wrong.



If thats the case, you can use 'map' function. Also, I think the inc2 one line # 1 is typo, I corrected it.



var inc1 = {


  num: 'INC111',


  sd: 'email'


};


var inc2 = {


  num: 'INC222',


  foo: 'internet'


}




var arr = [];


arr.push(inc2,inc1);




pos = arr.map(function(input) { return input.num; }).indexOf('INC111');




gs.log(pos);



Hope this helps. Mark the answer as correct/helpful based on impact.



Thanks


Antin


Yes thats what i wanted. I will try, and revert back