从Ember Lodash找到嵌套的属性,然后选择该值



我是JavaScript的新手。

我想检查特定的嵌套属性是否存在于一系列项目中,例如(

[{
    "_id" : ObjectId("5c4ec057e21b840001968d31"),
    "status" : "ACTIVE",
    "customerId" : "sample-book",
    "bookInfo" : {
        "bookChunks" : [ 
            {
                "key" : "Name",
                "value" : "test"
            }, 
            {
                "key" : "Surname1",
                "value" : "testtt"
            }, 
            {
                "key" : "user-contact",
                "value" : "sample-value",
                "ContactList" : {
                    "id" : "sample-id",
                    "timeStamp" : "Tue, 20 Sep 2016 07:49:25 +0000",
                    "contacts" : [ 
                        {
                            "id" : "contact-id1",
                            "name" : "Max Muller",
                            "phone_number" : "+XXXXXXX"
                        }, 
                        {
                            "id" : "contact-id2",
                            "name" : "Max Muller",
                            "phone_number" : "+XXXXXXX"
                        }
                    ]
                }
            }
        ]
    }
},
{
    "_id" : ObjectId("5c4ec057e21b840001968d32"),
    "status" : "ACTIVE",
    "customerId" : "sample-book1",
    "bookInfo" : {
        "bookChunks" : [ 
            {
                "key" : "Name",
                "value" : "test"
            }, 
            {
                "key" : "Surname1",
                "value" : "testtt"
            }
        ]
    }
}]

在这里,我想找到是否有任何项目 ContactList 联系人存在。如果在场,请将项目放在单独的列表中。

我正在使用Ember-Lodash。使用普通的JavaScript或Lodash对我来说很好。任何帮助都将不胜感激。

您可以使用filtersome。这将返回所有具有至少一个对象的对象,其中 ContactList属性 bookInfo.bookChunks数组中的属性。

const input=[{"_id":"5c4ec057e21b840001968d31","status":"ACTIVE","customerId":"sample-book","bookInfo":{"bookChunks":[{"key":"Name","value":"test"},{"key":"Surname1","value":"testtt"},{"key":"user-contact","value":"sample-value","ContactList":{"id":"sample-id","timeStamp":"Tue, 20 Sep 2016 07:49:25 +0000","contacts":[{"id":"contact-id1","name":"Max Muller","phone_number":"+XXXXXXX"},{"id":"contact-id2","name":"Max Muller","phone_number":"+XXXXXXX"}]}}]}},{"_id":"5c4ec057e21b840001968d32","status":"ACTIVE","customerId":"sample-book1","bookInfo":{"bookChunks":[{"key":"Name","value":"test"},{"key":"Surname1","value":"testtt"}]}}]
const output = input.filter(o => 
  o.bookInfo.bookChunks.some(c => "ContactList" in c)
)
console.log(output)

如果您只想检查任何对象是否具有ContactList,则可以用另一个some

替换filter

(注意:这是假设bookInfo.bookChunks不会被不确定。否则,您必须在使用嵌套属性之前添加未定义的支票(

最新更新