How can I get the index from a JSON object with value?
You can use Array.findIndex
.
var data= [{
"name": "placeHolder",
"section": "right"
}, {
"name": "Overview",
"section": "left"
}, {
"name": "ByFunction",
"section": "left"
}, {
"name": "Time",
"section": "left"
}, {
"name": "allFit",
"section": "left"
}, {
"name": "allbMatches",
"section": "left"
}, {
"name": "allOffers",
"section": "left"
}, {
"name": "allInterests",
"section": "left"
}, {
"name": "allResponses",
"section": "left"
}, {
"name": "divChanged",
"section": "right"
}];
var index = data.findIndex(obj => obj.name=="allInterests");
console.log(index);
You will have to use Array.find
or Array.filter
or Array.forEach
.
Since your value is array and you need the position of the element, you will have to iterate over it.
Array.find
var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];
var index = -1;
var val = "allInterests"
var filteredObj = data.find(function(item, i){
if(item.name === val){
index = i;
return i;
}
});
console.log(index, filteredObj);
Array.findIndex() @Ted Hopp's suggestion
var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];
var val = "allInterests"
var index = data.findIndex(function(item, i){
return item.name === val
});
console.log(index);
Default Array.indexOf()
will match searchValue to current element and not its properties. You can refer Array.indexOf - polyfill on MDN
Traverse through the array and find the index of the element which contains a key name
and has the value as the passed param.
var data = [{
"name": "placeHolder",
"section": "right"
}, {
"name": "Overview",
"section": "left"
}, {
"name": "ByFunction",
"section": "left"
}, {
"name": "Time",
"section": "left"
}, {
"name": "allFit",
"section": "left"
}, {
"name": "allbMatches",
"section": "left"
}, {
"name": "allOffers",
"section": "left"
}, {
"name": "allInterests",
"section": "left"
}, {
"name": "allResponses",
"section": "left"
}, {
"name": "divChanged",
"section": "right"
}];
Array.prototype.getIndexOf = function(el) {
var arr = this;
for (var i=0; i<arr.length; i++){
console.log(arr[i].name);
if(arr[i].name==el){
return i;
}
}
return -1;
}
alert(data.getIndexOf("allResponses"));