JavaScript搜索对象中的对象并返回两个元素

时间:2018-03-31 09:00:28

标签: javascript object search

我有一个这样的对象:

{
    "Peter": {
        "data": {
            "id": 104,
            "budget": 3400
        },
        "items": {
            "shoes": {
                "sales": 72,
                "intake": 576
            },
            "books": {
                "sales": 14,
                "intake": 70
            } 
        }
    },
    "Bradley": {...}
}

Peter对象与其他名称重复多次。

现在我想搜索一下让我们说books

如果在对象的某处找到books,它应该返回找到的对象books中的元素及其值。

我也想知道找到了哪个大对象books。所以在这种情况下它应该返回Peter

如果在多个对象中找到books,它应该以数组形式返回结果。

我知道如何通过使用find()方法搜索其中一个属性来获取对象,但我想知道当您搜索的对象具有名称时如何执行此操作你以前不知道。

1 个答案:

答案 0 :(得分:0)

Object.entries()Array.prototype.filter()Array.prototype.every()Object.values()可以组合在一起构建array people predicated items }} // Input. const people = {"Peter": {"data": {"id": 104, "budget": 3400}, "items": {"shoes": {"sales": 72, "intake": 576}, "books": {"sales": 14, "intake": 70 }}}} // People With. const peopleWith = (o, ...p) => Object.entries(o).filter(([person, attributes]) => p.every(x => Object.values(attributes.items[x] || {}).length)) // Output. const positive = peopleWith(people, 'books') console.log('Found', positive) // [[person, attributes] ...] const compound = peopleWith(people, 'books', 'shoes') console.log('Compound', compound) // People with books and shoes. const negative = peopleWith(people, 'books', 'shoes', 'hats') console.log('None Found', negative) // []

请参阅下面的实例。

public class MyRouteConfiguration extends CamelConfiguration {

    @Autowire
    private MyRouteBuilder myRouteBuilder;

    @Autowire
    private MyAnotherRouteBuilder myAnotherRouteBuilder;

    @Override
    public List<RouteBuilder> routes() {
        return Arrays.asList(myRouteBuilder, myAnotherRouteBuilder);
    }
}