在对象数组中查找最后一个匹配的对象 [英] Find last matching object in array of objects

查看:62
本文介绍了在对象数组中查找最后一个匹配的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组.我需要获取最后一个对象的对象类型(在此示例中为形状"),将其删除,然后在数组中找到具有相同类型的前一个对象的索引,例如形状".

I have an array of objects. I need to get the object type ("shape" in this example) of the last object, remove it, and then find the index of the previous object in the array that has the same type, e.g. "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

所以,很明显,这个例子中的类型将是圆形".但我不是在寻找圆形"的数组值.我正在寻找fruit.shape = round 的地方.

So, obviously the type in this example will be "round". But I'm not looking for an array value of "round". I'm looking for where fruits.shape = round.

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

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

But just using that doesn't work. I'm sure I'm missing something simple. How do I find the last item in the array where the shape of the object = round?

推荐答案

var previousInShapeType, index = fruits.length - 1;
for ( ; index >= 0; index--) {
    if (fruits[index].shape == currentShape) {
        previousInShapeType = fruits[index];
        break;
    }
}

您也可以通过数组向后循环.

You can also loop backwards through array.

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

这篇关于在对象数组中查找最后一个匹配的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆