在字典中查找第三个元素值

时间:2018-05-01 13:52:23

标签: javascript

我需要知道前两个值的字典数组的第三个元素。例如:

    var dict = [{name: "A", game: "X", number: 5},
               {name: "B", game: "X", number: 3},
               {name: "A", game: "Y", number: 1},
               {name: "C", game: "Z", number: 2}]

因此,如果我找到 名称:“A” 游戏:“X” ,则会返回< strong> number:5 或只是 5 。如果它是可行的,那么在该元素的数组中获取索引,例如在这种情况下,索引将是 0 ,因为它位于 中字典[0]

3 个答案:

答案 0 :(得分:0)

如果要从数组中查找特定对象并将其返回,则可以使用find()方法。

 var dict = [{name: "A", game: "X", number: 5}, {name: "B", game: "X", number: 3}, {name: "A", game: "Y", number: 1}, {name: "C", game: "Z", number: 2}]
               
const obj = dict.find(({name, game}) => name == 'A' && game == 'X');
if(obj) console.log(obj.number)

如果你想获得索引,你可以使用findIndex方法,如果找到元素则返回索引,否则返回-1。

 var dict = [{name: "A", game: "X", number: 5}, {name: "B", game: "X", number: 3}, {name: "A", game: "Y", number: 1}, {name: "C", game: "Z", number: 2}]
               
const index = dict.findIndex(({name, game}) => name == 'A' && game == 'X');
console.log(index)

答案 1 :(得分:0)

ES6

您可以使用数组的find()方法

  

find()方法返回数组中第一个满足提供的测试函数的元素的值。否则返回undefined

<强>样本

&#13;
&#13;
const arr = [{name: "A", game: "X", number: 5},
{name: "B", game: "X", number: 3},
{name: "A", game: "Y", number: 1},
{name: "C", game: "Z", number: 2}];
               
let result = arr.find( ({ name, game }) => name=='A' && game=='X');               
               
if(result){
  console.log(result.number)
}
&#13;
.as-console-wrapper {max-height: 100% !important;top: 0;}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

如果我没有误解你的问题。您可以尝试使用find()findIndex()

var dict = [{name: "A", game: "X", number: 5},
               {name: "B", game: "X", number: 3},
               {name: "A", game: "Y", number: 1},
               {name: "C", game: "Z", number: 2}];

//find other property value based on some property value
var find = dict.find(elm => elm.name ==='A' && elm.game==='X').number;

//find the index based on property value
var findIndex = dict.findIndex(elm => elm.name==='A' && elm.game==='X');

console.log(find);
console.log(findIndex);