在对象数组中查找最后一个匹配的对象

新手上路,请多包涵

我有一组对象。我需要获取最后一个对象的对象类型(本例中为“shape”),将其删除,然后在数组中找到具有相同类型(例如“shape”)的前一个对象的索引。

 var fruits = [
    {
        shape: round,
        name: orange
    },
    {
        shape: round,
        name: apple
    },
    {
        shape: oblong,
        name: zucchini
    },
    {
        shape: oblong,
        name: banana
    },
    {
        shape: round,
        name: grapefruit
    }
]

// What's the shape of the last fruit
var currentShape =  fruits[fruits.length-1].shape;

// Remove last fruit
fruits.pop(); // grapefruit removed

// Find the index of the last round fruit
var previousInShapeType = fruits.lastIndexOf(currentShape);
    // should find apple, index = 1

所以,显然这个例子中的类型是“round”。但我不是在寻找“round”的数组值。我正在寻找 fruits.shape = round 的位置。

 var previousInShapeType = fruits.lastIndexOf(fruits.shape = currentShape);

但是仅仅使用它是行不通的。我确定我错过了一些简单的东西。如何找到数组中对象形状 = 圆形的最后一项?

原文由 Graeck 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 829
2 个回答
var previousInShapeType, index = fruits.length - 1;
for ( ; index >= 0; index--) {
    if (fruits[index].shape == currentShape) {
        previousInShapeType = fruits[index];
        break;
    }
}

您还可以通过数组向后循环。

小提琴:http: //jsfiddle.net/vonn9xhm/

原文由 AtheistP3ace 发布,翻译遵循 CC BY-SA 3.0 许可协议

var fruit = fruits.slice().reverse().find(fruit => fruit.shape === currentShape);

原文由 Luke Liu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题