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

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

问题描述

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

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

所以,显然这个例子中的类型将是圆的。但我不是在寻找圆的数组值。我正在寻找fruits.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天全站免登陆