This question already has answers here:
How to filter object array based on attributes?
                                
                                    (13个回答)
                                
                        
                                5年前关闭。
            
                    
我有一个包含JSONArray这样的JSONObjects{firstname:'John', lastname:'Doe'}

有没有办法直接选择所有具有JSONObjectsfirstname == 'John',或者唯一的方法是循环数组,测试字段名并将所有匹配的对象保存在另一个数组中?

谢谢

最佳答案

filter method应该可以解决问题。



var jsonArrayString = '[{"firstname": "John","otherProp": "otherValue"},{"firstname": "other Name", "otherProp": "otherValue"}]';

var jsonArray = JSON.parse(jsonArrayString);

var filteredArray = jsonArray.filter(function(element) {
  return element.firstname === "John";
});

console.log(filteredArray);





建议:
09-17 23:33