如果我有这样的数组:
var array1 =
[
{"phraseId":"abc",
"keyword":"bb",
"posId":1},
{"phraseId":"def",
"keyword":"bb",
"posId":1},
]
Run Code Online (Sandbox Code Playgroud)
如何才能发现具有"def"的phraseId的对象具有第二个位置?
您可以映射对象并仅返回目标字段,然后使用内置indexOf来获取位置:
array1.map(item => item.phraseId).indexOf('def')
Run Code Online (Sandbox Code Playgroud)
使用本机JavaScript findIndex方法.
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);Run Code Online (Sandbox Code Playgroud)
对于较旧的浏览器检查polyfill选项.
具有ES6箭头功能
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);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |