If I have an array like this:
var array1 =
[
{"phraseId":"abc",
"keyword":"bb",
"posId":1},
{"phraseId":"def",
"keyword":"bb",
"posId":1},
]
How can I find out that the object with phraseId of "def" has the 2nd position?
If I have an array like this:
var array1 =
[
{"phraseId":"abc",
"keyword":"bb",
"posId":1},
{"phraseId":"def",
"keyword":"bb",
"posId":1},
]
How can I find out that the object with phraseId of "def" has the 2nd position?
You could map your object and only return the target field, and then use the built in indexOf
to get the position:
array1.map(item => item.phraseId).indexOf('def')
Use native JavaScript findIndex
method.
var array1 = [{
"phraseId": "abc",
"keyword": "bb",
"posId": 1
}, {
"phraseId": "def",
"keyword": "bb",
"posId": 1
}, ];
var pos = array1.findIndex(function(v) {
// set your condition for finding object
return v.phraseId == 'def';
// add `1` since you want to count from `1`
}) + 1;
console.log("Position of the object " + pos);
For older browser check polyfill option.
With ES6 arrow function
var array1 = [{
"phraseId": "abc",
"keyword": "bb",
"posId": 1
}, {
"phraseId": "def",
"keyword": "bb",
"posId": 1
}, ];
var pos = array1.findIndex(v => v.phraseId == 'def') + 1;
console.log("Position of the object " + pos);
It works this way :
array1.forEach((elem, index) => {if (elem.phraseId === "def")
console.log("index = " + index);
});
Assuming that your key is know (that you know you are looking for a phraseId
always) then you can simply iterate through the array with a normal for
loop if you are using "traditional" JS, or with a forEach
if you are using ES6. Here's the simple for
implementation.
for (var i = 0; i < array1.length; i++ ){
if(array[i].phraseId === 'def') {
// we know "i" is the index, so do something...
}
}
To make it more generic so you can search any array for any key, make a function of it that returns the index:
function whatIndex (arr, key, val) {
for (var i = 0; i < arr.length; i++) {
if( arr[i][key] === val ) {
return i;
}
}
}