How to get only particular object property with values from an json array in javascript

private int getPosition(JSONArray jsonArray) throws JSONException {
        for(int index = 0; index < jsonArray.length(); index++) {
            JSONObject jsonObject = jsonArray.getJSONObject(index);
            if(jsonObject.getString("name").equals("apple")) {
                return index; //this is the index of the JSONObject you want
            } 
        }
        return -1; //it wasn't found at all
    }
/**
 * Function for getting an object with a specific name from an array.
 * 
 * @param arr The JsonArray to check in.
 * @param name The name to check for.
 * @return The JsonObject with a matching name field or null if none where found. 
 */
public static JsonObject getObjectWithName(JsonArray arr, String name)
{
    //Iterate over all elements in that array
    for(JsonElement elm : arr)
    {
        if(elm.isJsonObject()) //If the current element is an object.
        {
            JsonObject obj = elm.getAsJsonObject();

            if(obj.has("name")) //If the object has a field named "name"
            {
                JsonElement objElm = obj.get("name"); //The value of that field

                //Check if the value is a string and if it equals the given name
                if(objElm.isJsonPrimitive() && objElm.getAsJsonPrimitive().isString() && objElm.getAsString().equals(name))
                {
                    return obj;
                }
            }
        }
    }

    //Nothing matching was found so return null
    return null;
}

Leave a comment

Your email address will not be published. Required fields are marked *