简体   繁体   English

如何从对象数组中获取项目

[英]How to get items from an array of objects

I used jQuery.parseJSON to parse a JSON of objects that looks like this (Chrome Developers Console): 我使用jQuery.parseJSON解析了如下所示的对象的JSON(Chrome开发者控制台):

[Object, Object, Object, Object]
0: Object
    feedback_q1: "lol"
    subtotal: "13"
    __proto__: Object
1: Object
    feedback_q1: "lal"
    subtotal: "3"
    __proto__: Object
2: Object
3: Object
4: Object

How can I pick, using javascript or jQuery, each object (not using loops) and its properties? 如何使用javascript或jQuery选择每个对象(不使用循环)及其属性?

I think 我认为

JSONObject[0]

should retrieve the 1st object in your JSON object. 应该在JSON对象中检索第一个对象。 You can then get its properties by just doing 然后,您只需执行以下操作即可获取其属性

JSONObject[0].subtotal

If you know that you want to get prop1 value from X th element than json_objects[X].prop1 . 如果您知道要从第X个元素而不是json_objects[X].prop1获得prop1值。 Is there a real-life scenario when you want to do this? 您想做一个现实生活中的场景吗?

Maybe you want ed to get the element where... 也许您想让ed在哪里获取元素...

If you want to get element where prop1 value is 'lol' then you can use JQuery grep 如果要获取prop1值为'lol'元素,则可以使用JQuery grep

$.grep(json_objects, function(o){ return o.prop1 == 'lol'; });

The result of $.grep is an array with the items found which match your criteria. $.grep的结果是一个数组,其中找到符合您条件的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM