这是我的JSON对象,我希望在Javascript中找到所有具有Last Name = Smith和Age 36的元素。有没有聪明的方法,或者我必须通过所有数据循环两次?
[
{
"Name": "John",
"Last Name": "Smith",
"Age": "36",
"Hobbies": "Fishing, Racecars"
},
{
"Name": "John",
"Last Name": "Derre",
"Age": "64",
"Hobbies": ""
},
{
"Name": "James",
"Last Name": "Smith",
"Age": "36",
"Hobbies": "Computer"
},
{
"Name": "John",
"Last Name": "Do",
"Age": "25",
"Hobbies": "Comics, Music"
}
]
答案 0 :(得分:3)
您可以使用Array.filter
限制匹配项目:
const matches = data.filter(item => item['Last Name'] === "Smith" && item.Age === "36")
答案 1 :(得分:0)
您可以将对象用作搜索参数
{
'Last Name': 'Smith',
'Age': '36'
}
对更多属性进行更动态的过滤。
var array = [{ Name: "John", "Last Name": "Smith", Age: "36", Hobbies: "Fishing, Racecars" }, { Name: "John", "Last Name": "Derre", Age: "64", Hobbies: "" }, { Name: "James", "Last Name": "Smith", Age: "36", Hobbies: "Computer" }, { Name: "John", "Last Name": "Do", Age: "25", Hobbies: "Comics, Music" }],
search = { 'Last Name': 'Smith', Age: '36' },
result = array.filter((keys => o => keys.every(k => o[k] === search[k]))(Object.keys(search)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:-1)
下划线JS库有一些方便的方法来处理数据集合 - 例如,select方法
var found = _.select(userInfo, function(node){
return (node.Name === "John" && node.Age === "25")
});
console.dir (found);