Get index in object javascript

For example, I have:

var Data = [
  { id_list: 1, name: 'Nick', token: '312312' },
  { id_list: 2, name: 'John', token: '123123' },
]

Then, I want to sort/reverse this object by name, for example. And then I want to get something like this:

var Data = [
  { id_list: 2, name: 'John', token: '123123' },
  { id_list: 1, name: 'Nick', token: '312312' },
]

And now I want to know the index of the object with property name='John' to get the value of the property token.

How do I solve the problem?

Get index in object javascript

asked Aug 24, 2011 at 14:13

5

Since the sort part is already answered. I'm just going to propose another elegant way to get the indexOf of a property in your array

Your example is:

var Data = [
    {id_list:1, name:'Nick', token:'312312'},
    {id_list:2, name:'John', token:'123123'}
]

You can do:

var index = Data.map(function(e) { return e.name; }).indexOf('Nick');

Array.prototype.map is not available on Internet Explorer 7 or Internet Explorer 8. ES5 Compatibility

And here it is with ES6 and arrow syntax, which is even simpler:

const index = Data.map(e => e.name).indexOf('Nick');

xxx

1,1331 gold badge11 silver badges22 bronze badges

answered Apr 4, 2014 at 13:54

German AttanasioGerman Attanasio

20.4k7 gold badges47 silver badges63 bronze badges

11

If you're fine with using ES6, arrays now have the findIndex function. Which means you can do something like this:

const index = Data.findIndex(item => item.name === 'John');

Get index in object javascript

answered Sep 16, 2016 at 10:19

Get index in object javascript

silverlight513silverlight513

4,8123 gold badges25 silver badges36 bronze badges

5

As the other answers suggest, looping through the array is probably the best way. But I would put it in its own function, and make it a little more abstract:

function findWithAttr(array, attr, value) {
    for(var i = 0; i < array.length; i += 1) {
        if(array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}

var Data = [
    {id_list: 2, name: 'John', token: '123123'},
    {id_list: 1, name: 'Nick', token: '312312'}
];

With this, not only can you find which one contains 'John', but you can find which contains the token '312312':

findWithAttr(Data, 'name', 'John'); // returns 0
findWithAttr(Data, 'token', '312312'); // returns 1
findWithAttr(Data, 'id_list', '10'); // returns -1

The function returns -1 when not found, so it follows the same construct as Array.prototype.indexOf().

Get index in object javascript

answered Aug 24, 2011 at 15:45

Chris PickettChris Pickett

2,8121 gold badge13 silver badges7 bronze badges

3

If you're having issues with Internet Explorer, you could use the map() function which is supported from 9.0 onward:

var index = Data.map(item => item.name).indexOf("Nick");

Get index in object javascript

answered Jan 3, 2019 at 1:33

Get index in object javascript

Alain T.Alain T.

35.4k4 gold badges31 silver badges48 bronze badges

1

var index = Data.findIndex(item => item.name == "John")

Which is a simplified version of:

var index = Data.findIndex(function(item){ return item.name == "John"})

From mozilla.org:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

answered Mar 19, 2018 at 19:29

edankedank

5896 silver badges16 bronze badges

4

Only way known to me is to loop through all array:

var index = -1;
for(var i=0; i

Or case insensitive:

var index = -1;
for(var i=0; i

On result variable index contain index of object or -1 if not found.

Get index in object javascript

answered Aug 24, 2011 at 14:23

Andrew D.Andrew D.

7,9803 gold badges20 silver badges23 bronze badges

A prototypical way

(function(){
  if (!Array.prototype.indexOfPropertyValue){
       Array.prototype.indexOfPropertyValue = function(prop, value){
      for (var index = 0; index < this.length; index++){
        if (this[index][prop]){
          if (this[index][prop] == value){
            return index;
          }
        }
       }
      return -1;
    }
  }
 })();

 // Usage:
 var Data = [
   {id_list:1, name:'Nick', token:'312312'}, {id_list:2, name:'John', token:'123123'}];

 Data.indexOfPropertyValue('name', 'John'); // Returns 1 (index of array);
 Data.indexOfPropertyValue('name', 'Invalid name') // Returns -1 (no result);
 var indexOfArray = Data.indexOfPropertyValue('name', 'John');
 Data[indexOfArray] // Returns the desired object.

Get index in object javascript

answered Jul 24, 2013 at 11:22

1

you can use filter method

 const filteredData = data.filter(e => e.name !== 'john');

answered Nov 22, 2021 at 15:32

Get index in object javascript

Sakhri HoussemSakhri Houssem

8652 gold badges14 silver badges30 bronze badges

Just go through your array and find the position:

var i = 0;
for(var item in Data) {
    if(Data[item].name == 'John')
        break;
    i++;
}
alert(i);

answered Aug 24, 2011 at 14:24

Sascha GalleySascha Galley

15.2k5 gold badges36 silver badges51 bronze badges

4

let indexOf = -1;
let theProperty = "value"
let searchFor = "something";

theArray.every(function (element, index) {

    if (element[theProperty] === searchFor) {
        indexOf = index;
        return false;
    }
    return true;
});

answered Sep 4, 2017 at 16:54

Get index in object javascript

collection.findIndex(item => item.value === 'smth') !== -1

answered Jan 26, 2018 at 16:08

Get index in object javascript

2

You can use Array.sort using a custom function as a parameter to define your sorting mechanism.

In your example, it would give:

var Data = [
    {id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
]

Data.sort(function(a, b){
    return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
});

alert("First name is : " + Data[0].name); // alerts 'John'
alert("Second name is : " + Data[1].name); // alerts 'Nick'

The sort function must return either -1 if a should come before b, 1 if a should come after b and 0 if both are equal. It's up to you to define the right logic in your sorting function to sort the array.

Missed the last part of your question where you want to know the index. You would have to loop through the array to find that as others have said.

Get index in object javascript

answered Aug 24, 2011 at 14:24

This might be useful:

function showProps(obj, objName) {
  var result = "";
  for (var i in obj)
    result += objName + "." + i + " = " + obj[i] + "\n";
  return result;
}

I copied this from Working with objects.

Get index in object javascript

answered Feb 4, 2012 at 8:46

AshishAshish

1,17111 silver badges12 bronze badges

Use a small workaround:

Create a new array with names as indexes. After that all searches will use indexes. So, only one loop. After that you don't need to loop through all elements!

var Data = [
    {id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
    ]
var searchArr = []
Data.forEach(function(one){
  searchArr[one.name]=one;
})
console.log(searchArr['Nick'])

http://jsbin.com/xibala/1/edit

Live example.

Get index in object javascript

answered Jan 24, 2015 at 9:01

1

I extended Chris Pickett's answer, because in my case I needed to search deeper than one attribute level:

function findWithAttr(array, attr, value) {
  if (attr.indexOf('.') >= 0) {
    var split = attr.split('.');
    var attr1 = split[0];
    var attr2 = split[1];
    for(var i = 0; i < array.length; i += 1) {
      if(array[i][attr1][attr2] === value) {
        return i;
      }
    }
  } else {
    for(var i = 0; i < array.length; i += 1) {
      if(array[i][attr] === value) {
        return i;
      }
    }
  };
};

You can pass 'attr1.attr2' into the function.

Get index in object javascript

answered Nov 30, 2015 at 17:38

Get index in object javascript

Ed SheeEd Shee

9311 gold badge7 silver badges22 bronze badges

Use this:

Data.indexOf(_.find(Data, function(element) {
  return element.name === 'John';
}));

It is assuming you are using Lodash or Underscore.js.

Get index in object javascript

answered Jan 18, 2017 at 11:46

Get index in object javascript

ElloneEllone

3,50211 gold badges37 silver badges67 bronze badges

var fields = {
  teste:
  {
    Acess:
    {
      Edit: true,
      View: false
    }
  },
  teste1:
  {
    Acess:
    {
      Edit: false,
      View: false
    }
  }
};

console.log(find(fields,'teste'));

function find(fields,field) {
  for(key in fields) {
    if(key == field) {
      return true;
    }
  }
  return false;
}

If you have one Object with multiple objects inside, if you want know if some object are include on Master object, just use find(MasterObject, 'Object to Search'). This function will return the response if it exists or not (TRUE or FALSE). I hope to help with this - can see the example on JSFiddle.

Get index in object javascript

answered Jul 18, 2017 at 14:40

2

If you want to get the value of the property token then you can also try this:

    let data=[
      { id_list: 1, name: 'Nick', token: '312312' },
      { id_list: 2, name: 'John', token: '123123' },
    ]

    let resultingToken =  data[_.findKey(data,['name','John'])].token

where _.findKey is a Lodash function.

Get index in object javascript

answered Nov 14, 2019 at 12:00

Akash SinghAkash Singh

5374 silver badges7 bronze badges

You can use findIndex in Lodash library.

Example:

var users = [
{ 'user': 'barney',  'active': false },
{ 'user': 'fred',    'active': false },
{ 'user': 'pebbles', 'active': true }
            ];

_.findIndex(users, function(o) { return o.user == 'barney'; });
// => 0

// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user': 'fred', 'active': false });
// => 1

// The `_.matchesProperty` iteratee shorthand.
_.findIndex(users, ['active', false]);
// => 0

// The `_.property` iteratee shorthand.
_.findIndex(users, 'active');
// => 2

answered Aug 29, 2021 at 12:22

Get index in object javascript

Iman MarashiIman Marashi

5,34736 silver badges50 bronze badges

Alternatively to German Attanasio Ruiz's answer, you can eliminate the second loop by using Array.reduce() instead of Array.map();

var Data = [
    { name: 'hypno7oad' }
]
var indexOfTarget = Data.reduce(function (indexOfTarget, element, currentIndex) {
    return (element.name === 'hypno7oad') ? currentIndex : indexOfTarget;
}, -1);

Get index in object javascript

answered Nov 4, 2014 at 20:45

hypno7oadhypno7oad

1,4311 gold badge19 silver badges28 bronze badges

Maybe the Object.keys, Object.entries, and Object.values methods might help.

answered Apr 5 at 1:44

Get index in object javascript

milahmilah

11 bronze badge

1

Using Underscore.js:

var index = _.indexOf(_.pluck(item , 'name'), 'Nick');

Get index in object javascript

answered Mar 10, 2020 at 6:04

Get index in object javascript

M Faisal HameedM Faisal Hameed

6531 gold badge6 silver badges22 bronze badges

Can we find index of object in JavaScript?

JavaScript findIndex() Method: This method returns the index of the first element in an array that satisfies the condition. If this method finds an array element for which the function returns a true value, this method returns the index of that array element and stops, Otherwise, it returns -1.

How do you find the index of an object in an object?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How do you get a specific value from an object in JavaScript?

How to get Keys, Values, and Entries in JavaScript Object?.
Object.keys(obj) – returns all the keys of object as array..
Object.values(obj) – returns all the values of the object as array..
Object.entries(obj) – returns an array of [key, value].

How do you find the index of an element?

To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error. To fix this issue, you need to use the in operator.