10

for example I have this array :

  $scope.records = [
    {
      "Name" : "Alfreds Futterkiste",
      "Country" : "Germany"
    },
    {
      "Name" : "Berglunds snabbköp",
      "Country" : "Sweden"
    },
    {
      "Name" : "Centro comercial Moctezuma",
      "Country" : "Mexico"
    },
    {
      "Name" : "Ernst Handel",
      "Country" : "Austria"
    }
  ];

How to get value index from object? with example "Country" : "Austria" this index is 3

1
  • this should have been an easy web search Commented Oct 12, 2016 at 13:16

7 Answers 7

19

You could use Array.findIndex in the latest browsers, but there's no support for this in Internet Explorer, only Edge

let $scope = {};

$scope.records = [
    {
      "Name" : "Alfreds Futterkiste",
      "Country" : "Germany"
    },
    {
      "Name" : "Berglunds snabbköp",
      "Country" : "Sweden"
    },
    {
      "Name" : "Centro comercial Moctezuma",
      "Country" : "Mexico"
    },
    {
      "Name" : "Ernst Handel",
      "Country" : "Austria"
    }
];

let index = $scope.records.findIndex( record => record.Country === "Austria" );

console.log(index); // 3

For support in IE9 and up, you could use Array.some instead

var $scope = {};

$scope.records = [{
  "Name": "Alfreds Futterkiste",
  "Country": "Germany"
}, {
  "Name": "Berglunds snabbköp",
  "Country": "Sweden"
}, {
  "Name": "Centro comercial Moctezuma",
  "Country": "Mexico"
}, {
  "Name": "Ernst Handel",
  "Country": "Austria"
}];

var index = -1;

$scope.records.some(function(obj, i) {
  return obj.Country === "Austria" ? index = i : false;
});

console.log(index);

Sign up to request clarification or add additional context in comments.

6 Comments

You could modify it slightly to use array.some. At least then it would stop iterating once you have found your index, same browser support too.
@ste2425 - I could, I could even add a ternary
You are not returning anything in true case. This is as good as return false and loop will not end at first match. I'd suggest, obj.Country === 'Austria' && (index = i); return index != -1
@Rajesh - it works because the assignment is truthy if it's any number above 0, and if it's 0, then it's the first one, and can just return -> jsfiddle.net/adeneo/jgwu6v1j
I did not know this hack. Nice.
|
14

You can use array.findIndex for this:

var d = [{
  "Name": "Alfreds Futterkiste",
  "Country": "Germany"
}, {
  "Name": "Berglunds snabbköp",
  "Country": "Sweden"
}, {
  "Name": "Centro comercial Moctezuma",
  "Country": "Mexico"
}, {
  "Name": "Ernst Handel",
  "Country": "Austria"
}];
var searchCountry = "Austria"
var index = d.findIndex(x=>x.Country === searchCountry)
console.log(index)

Note: array.findIndex is a part of ES6.

Comments

3
Use findIndex method - 
   var index = $scope.records.findIndex(x=>x.Country==='Austria')

Comments

0
function getIndexByCountryName(country)
    var found = $scope.records.find(function(item){return item.Country === country});
    return $scope.records.indexOf(found);
}

Comments

0

You can do which returns the countries and then finds the country.

$scope.records.map((item) => { return item.Country;}).indexOf('Austria')

The problem with the above code iterates once through each element to generate a map and then finds the index. You can use a simple for loop:

var index = (arr, k, v) => { 
   var i = -1;len = (arr || []).length;  
   for (i = 0; i < len; i++) { 
     if (arr[i][k] === v) 
       return i;
   }
   return -1;
} 

I noticed a lot of findIndex solutions. Please note: FindIndex method has been added to the ECMAScript 6 specification and may not be available in all JavaScript implementations yet as per MDN.

You can use the polyfill for findIndex(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) and use the findIndex solution that others suggested. If you do not want to use the polyfill you can use the map and indexOf that I put as solution.

Comments

0

I have registered this method and it works like charm,

Array.prototype.getIndexByValue = function (name, value) {
        for (var i = 0, len=this.length; i <len; i++) {
            if (this[i][name]) {
                if (this[i][name] === value) {
                    return i
                }
            }
        }
        return -1;
    };

var d = [{
  "Name": "Alfreds Futterkiste",
  "Country": "Germany"
}, {
  "Name": "Berglunds snabbköp",
  "Country": "Sweden"
}, {
  "Name": "Centro comercial Moctezuma",
  "Country": "Mexico"
}, {
  "Name": "Ernst Handel",
  "Country": "Austria"
}];


var index = d.getIndexByValue('Country','Austria');
console.log(index)//will print 3

1 Comment

You are leaking that variable i to window scope. Also if the value is not found return -1 instead of null to keep it consistent with the indexOf function.
0

Using a for - in loop as it is a JSON array, you can do this

for(i in records) {
if(records[i].country=="Austria") 
console.log("index is :"+ parseInt(i)); // print index
}

1 Comment

records is already a Javascript object. You do not need a JSON.parse. Also typeof i is string and not a number as is expected out of a index function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.